c# – 用户定义的值类型的装箱

c# – 用户定义的值类型的装箱,第1张

概述根据MSDN,如果定义了结构,该结构应该覆盖从对象类继承的所有方法.建议在调用任何继承的方法(如ToString)时避免不必要的装箱. 根据MSDN,为了确定是否以及何时发生装箱,可以在MSIL代码中找到IL指令“框”. 我写了下面的测试来看拳击. using System;namespace TestingBoxing{ public struct StructX { @H_502_6@ 根据MSDN,如果定义了结构,该结构应该覆盖从对象类继承的所有方法.建议在调用任何继承的方法(如ToString)时避免不必要的装箱.

根据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

解决方法 这可以通过查看Constrained的作用来解释.

字段通常受到约束,以便以标准方式使用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确定.

受约束的MSDN:http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.constrained%28v=vs.110%29.aspx

总结

以上是内存溢出为你收集整理的c# – 用户定义的值类型的装箱全部内容,希望文章能够帮你解决c# – 用户定义的值类型的装箱所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1219378.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存