拳击,对过去的事情? [英] Boxing, a thing of the past?

查看:161
本文介绍了拳击,对过去的事情?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一点做这个?

public static void Write<T>(T value)
{
    textWriter.Write(value.ToString());
}

......像预想的那样,以这样的:

...as supposed to this:

public static void Write(object value)
{
    textWriter.Write(value.ToString());
}

撇开明显的空取消引用可能性,如果我在这里写了很多使用这种方法的价值类型不会前要好得多,因为它有它自己的版本的写入方法调用,或只是会膨胀二进制了很多额外的code的生成条件?

Setting aside the obvious null dereference possibility, If I where to write a lot of value types using this method wouldn't the former be much better because it will have it's own version of the write method to call, or is it just gonna bloat the binary in terms of a lot of additional code being generated?

这样的事情性能言下之意可能是微不足道的,但我很好奇,它的很多不是提供过载为每BCL中的每个值类型,最喜欢的作家的首创置业已经在做更加紧凑。

The performance implication of such a thing might be negligible, but I'm curious, it's a lot more compact than providing an overload for each and every value type in the BCL, like most writers in the BCL already do.

推荐答案

据我了解,在这两种情况下发生拳。

From what I understand, in both cases boxing occurs.

后者是明显,因为该值已经盒装

The latter is obvious as the value is already boxed.

前者是不太明显的,但作为一个虚拟方法上调用值类型,它需要被装箱以执行 callvirt

The former is less obvious, but as a virtual method is called on a valuetype, it will need to be boxed to perform the callvirt.

编辑:我只是检查所发出的IL,并且在一般情况下,没有明确的拳击发生的历史。事情听起来很耳熟,但。

I just checked the emitted IL, and there is no explicit boxing occuring in the generic case. Something rings a bell though.

编辑2:我可能已经被混淆自己使用接口的情况下。有明确的拳击发生。

Edit 2: I might have been confusing myself with the case using interfaces. There clearly boxing occurs.

修改3:拳击确实发生,如果的ToString()不重写的值类型

Edit 3: Boxing does occur, if ToString() is not overriden in the value type.

我得到这个由ECMA-335第3部分第25页(仅指出过去的情况下):

I get this from ECMA-335 part 3 pg 25 (only noting the last case):

如果 thisType 的是一个值类型,    thisType 的未实现方法   随后的 PTR 的是废弃,彩盒   通过为本这个指针   方法的callvirt

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 of method

这最后一种情况只能发生在   方法对 System.Object的定义,    System.ValueType System.Enum 和   不是的 thisType 的覆盖。在这   最后一种情况,拳导致副本   要做出的原始对象,   然而,因为所有的方法上    System.Object的 System.ValueType ,和    System.Enum 不修改的状态   上述目的,该事实也不能   检测。

This last case can only occur when method was defined on System.Object, System.ValueType, or System.Enum and not overridden by thisType. In this last case, the boxing causes a copy of the original object to be made, however since all methods on System.Object, System.ValueType, and System.Enum do not modify the state of the object, this fact can not be detected.

修改4: <一个href="http://stackoverflow.com/questions/926352/how-is-valuetype-gettype-able-to-determine-the-type-of-the-struct">Here是SO 过类似的问题。

这篇关于拳击,对过去的事情?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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