关于装箱的一个问题
在《.NET框架程序设计》中有这样的一个例子:
using System;
struct Point : ICloneable
{
public Int32 x, y;
public override String ToString()
{
return String.Format("({0}, {1}", x, y);
}
public Object Clone()
{
return MemberwiseClone();
}
}
public class App
{
public static void Main()
{
Point p;
p.x = 10;
p.y = 20;
Console.WriteLine(p.ToString());
Console.WriteLine(p.GetType());
Point p2 = (Point)p.Clone();
ICloneable c = p2;
Object o = c.Clone();
p = (Point)o;
}
}
里面提到p在执行ToString方法的时候不会发生装箱。通过看IL代码确实是这么回事,但是再去查看Point的ToString方法的IL代码,发现在其中进行了装箱操作,那么是不是总的说来还是进行了装箱操作呢?
IL代码如下:
.method public hidebysig virtual instance string
ToString() cil managed
{
// Code size 37 (0x25)
.maxstack 3
.locals init (string V_0)
IL_0000: ldstr "({0}, {1}"
IL_0005: ldarg.0
IL_0006: ldfld int32 Point::x
IL_000b: box [mscorlib]System.Int32
IL_0010: ldarg.0
IL_0011: ldfld int32 Point::y
IL_0016: box [mscorlib]System.Int32
IL_001b: call string [mscorlib]System.String::Format(string,
object,
object)
IL_0020: stloc.0
IL_0021: br.s IL_0023
IL_0023: ldloc.0
IL_0024: ret
} // end of method Point::ToString
请各位高手指教。




































里面提到p在执行ToString方法的时候不会发生装箱。通过看IL代码确实是这么回事,但是再去查看Point的ToString方法的IL代码,发现在其中进行了装箱操作,那么是不是总的说来还是进行了装箱操作呢?
IL代码如下:
.method public hidebysig virtual instance string
ToString() cil managed
{
// Code size 37 (0x25)
.maxstack 3
.locals init (string V_0)
IL_0000: ldstr "({0}, {1}"
IL_0005: ldarg.0
IL_0006: ldfld int32 Point::x
IL_000b: box [mscorlib]System.Int32
IL_0010: ldarg.0
IL_0011: ldfld int32 Point::y
IL_0016: box [mscorlib]System.Int32
IL_001b: call string [mscorlib]System.String::Format(string,
object,
object)
IL_0020: stloc.0
IL_0021: br.s IL_0023
IL_0023: ldloc.0
IL_0024: ret
} // end of method Point::ToString
请各位高手指教。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】