加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 02:04:19 所属栏目:百科 来源:网络整理
导读:根据MSDN,如果定义了结构,该结构应该覆盖从对象类继承的所有方法.建议在调用任何继承的方法(如ToString)时避免不必要的装箱. 根据MSDN,为了确定是否以及何时发生装箱,可以在MSIL代码中找到IL指令“框”. 我写了下面的测试来看拳击. using System;namespace T
根据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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读