根据MSDN,为了确定是否以及何时发生装箱,可以在MSIL代码中找到IL指令“框”.
我写了下面的测试来看拳击.
using System; namespace TestingBoxing { public struct StructX { public int member1; public int member2; } public class Program { public static void Main(string[] args) { StructX s1; s1.member1 = 2; s1.member2 = 5; string str = s1.ToString(); Console.WriteLine(str); } } }
但是,尽管在结构定义中未调用ToString,但在下面的MSIL代码中无法看到装箱指令.
.method public hidebysig static void Main(string[] args) cil managed { .entrypoint // Code size 37 (0x25) .maxstack 2 .locals init ([0] valuetype TestingBoxing.StructX s1,[1] string str) IL_0000: ldloca.s s1 IL_0002: ldc.i4.2 IL_0003: stfld int32 TestingBoxing.StructX::member1 IL_0008: ldloca.s s1 IL_000a: ldc.i4.5 IL_000b: stfld int32 TestingBoxing.StructX::member2 IL_0010: ldloca.s s1 IL_0012: constrained. TestingBoxing.StructX IL_0018: callvirt instance string [mscorlib]System.Object::ToString() IL_001d: stloc.1 IL_001e: ldloc.1 IL_001f: call void [mscorlib]System.Console::WriteLine(string) IL_0024: ret } // end of method Program::Main
怎么解释?
参考文章:http://msdn.microsoft.com/en-us/library/ms973858.aspx#code-snippet-6
解决方法
字段通常受到约束,以便以标准方式使用callvirt,而无需明确选择框.它执行以下操作:
If thisType is a reference type (as opposed to a value type) then ptr is dereferenced and passed as the ‘this’ pointer to the callvirt of method.
If thisType is a value type and thisType implements method then ptr is passed unmodified as the ‘this’ pointer to a call method instruction,for the implementation of method by thisType.
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.
这意味着什么(如MSDN文章所述):
This last case can occur only when method was defined on Object,ValueType,or Enum and not overridden by thisType. In this case,the Boxing causes a copy of the original object to be made. However,because none of the methods of Object,and Enum modify the state of the object,this fact cannot be detected.
强调我的.基本上说如果拳击确实发生,则无法通过IL确定.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。