是否调用值类型的结果拳击在.NET的方法? [英] Does calling a method on a value type result in boxing in .NET?

查看:106
本文介绍了是否调用值类型的结果拳击在.NET的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚参加堆栈溢出问题的 一切都在.NET中反对呢? 的。

和一张海报(在接受的答案的评论)似乎认为,在执行上的值类型的方法调用导致了拳击。他指着我的 装箱和拆箱(C#编程指南) 的不完全指定使用情况下,我们描述了。

我不是一个信任的单一来源,所以我只是想获得关于这个问题的进一步反馈。我的直觉是,有没有拳击,但我的直觉不吸。 :D

要进一步阐述:

我使用的例子是:

  INT X = 5;
字符串s = x.ToString(); // 拳击??
 

拳击做的没有的发生,如果有问题的结构将覆盖从对象继承的方法,在这里接受的答案状态。

但是,如果结构不覆盖的方法,一个约束 CIL 的命令之前,一个callvirt执行。根据该文件,的 <一个href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.op$c$cs.constrained.aspx">Op$c$cs.Constrained现场 这导致在拳击

  

如果thisType是值类型和   thisType不实现方法   那么PTR被废弃,彩盒   通过为本这个指针   callvirt方法指令。

解决方案

这里的IL你的code:

  L_0001:ldc.i4.5 //获得5堆栈上
L_0002:stloc.0 //存储成X个
L_0003:ldloca.sx //获取堆栈x的地址
L_0005:呼叫实例字符串[mscorlib程序] System.Int32的::的ToString()//的ToString
L_000a:stloc.1 //将S
 

因此​​,在这种情况下,答案是否定的。

I was just participating in Stack Overflow question Is everything in .NET an object?.

And one poster (in comments of accepted answer) seemed to think that performing a method call on a value type resulted in boxing. He pointed me to Boxing and Unboxing (C# Programming Guide) which doesn't exactly specify the use case we're describing.

I'm not one to trust a single source, so I just wanted to get further feedback on the question. My intuition is that there is no boxing but my intuition does suck. :D

To further elaborate:

The example I used was:

int x = 5;
string s = x.ToString(); // Boxing??

Boxing does not occur if the struct in question overrides the method inherited from the object as the accepted answer here states.

However if the struct doesn't override the method, a "constrain" CIL command is executed prior to a callvirt. According to the documentation, OpCodes.Constrained Field, this results in boxing:

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.

解决方案

Here's the IL for your code:

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

So the answer in this case is no.

这篇关于是否调用值类型的结果拳击在.NET的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆