确实valueType.ToString()做的VALUETYPE铸造? [英] does valueType.ToString() does a cast on the valueType?

查看:132
本文介绍了确实valueType.ToString()做的VALUETYPE铸造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说,我在C#下面的代码

lets say, i have the following code in c#

int x = 0;
x.ToString();



做到这一点确实在内部x的拳击?
是有没有办法看到从Visual Studio这样?

does this internally does a boxing of x? Is there a way to see this happening from visual studio?

推荐答案

在这个特定的情况下,您使用的是 System.Int32 (一个 INT )。这种类型的重新定义的ToString 等于的GetHashCode ,所以没有拳击。

In this specific case, you are using a System.Int32 (an int). That type redefines ToString, Equals and GetHashCode, so no boxing.

如果您使用的是结构不重新定义的ToString 你有什么是约束callvirt System.Object.ToString()约束的定义:

If you use a struct that doesn't redefine ToString what you'll have is a constrained callvirt to System.Object.ToString(). The definition of constrained:

当一个callvirt方法指令已经被约束thisType前缀,如下所述指令被执行:

When a callvirt method instruction has been prefixed by constrained thisType, the instruction is executed as follows:


  • 如果thisType是值类型和thisType实现方法则PTR传递未修改的这个指针调用方法指令,由thisType的实现方法。

  • 如果thisType是值类型和thisType没有实现方法,那么PTR取消引用,盒装,并作为'这个'指针callvirt方法指令过去了。

  • 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.

所以没有拳击如果值类型实现了的ToString ,如果它没有实现它...有趣的有拳击。我不知道。

So there isn't boxing if the value type implements ToString and there is boxing if it doesn't implement it... Interesting. I didn't know.

有关非虚方法,如的GetType()中定义的 System.Object的的值类型总是装箱。

For non-virtual methods like GetType() that are defined in System.Object the value type is always boxed. Just tested with a:

5.GetType();



导致IL代码:

resulting IL code:

IL_0001: ldc.i4.5
IL_0002: box [mscorlib]System.Int32
IL_0007: call instance class [mscorlib]System.Type [mscorlib]System.Object::GetType()

这篇关于确实valueType.ToString()做的VALUETYPE铸造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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