我刚刚参加了 Stack Overflow 问题 Is everything in .NET an object? 。
一位发帖者(在已接受答案的评论中)似乎认为对值类型执行方法调用会导致装箱。他向我指出 Boxing and Unboxing (C# Programming Guide) 这并没有准确指定我们所描述的用例。
我不是一个相信单一来源的人,所以我只是想获得有关该问题的进一步反馈。我的直觉是没有拳击,但我的直觉确实很糟糕。 :D
进一步阐述:
我使用的示例是:
int x = 5;
string s = x.ToString(); // Boxing??
如果相关结构覆盖从对象继承的方法(如此处接受的答案所述),则装箱不会发生。
但是,如果结构体不重写该方法,则会出现“约束”CIL命令在 callvirt 之前执行。根据文档, OpCodes.Constrained Field ,这会导致拳击:
If thisType is a value type and thisType does not implement method then ptr is dereferenced, boxed, and passed as the 'this' pointer to the callvirt method instruction.
最佳答案
这是您的代码的 IL:
L_0001: ldc.i4.5 // get a 5 on the stack
L_0002: stloc.0 // store into x
L_0003: ldloca.s x // get the address of x on the stack
L_0005: call instance string [mscorlib]System.Int32::ToString() // ToString
L_000a: stloc.1 // store in s
所以在这种情况下答案是否定的。
关于.net - 对值类型调用方法是否会导致 .NET 中装箱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/436363/