铸造结构成一个通用的接口时,是否有拳击/拆箱? [英] Is there Boxing/Unboxing when casting a struct into a generic interface?

查看:107
本文介绍了铸造结构成一个通用的接口时,是否有拳击/拆箱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
结构,接口和拳击

从MSDN:的 http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx

拳击为值类型转换为类对象的或任何接口的此值类型实现类型的过程。

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type.

但对于通用接口?

例如, INT 从两个派生 IComparable的 IComparable的< INT方式>

让我们说我有下面的代码:

Let's say I have the following code:

void foo(IComparable value)    { /* etc. */ }
void bar(IComparable<T> value) { /* etc. */ }

void gizmo()
{
   int i = 42;

   bar(i); // is `i` boxed? I'd say YES
   foo(i); // is `i` boxed? I fear it is (but I hope for NO)
}



确实(或服用非泛型接口的任何功能)意味着将有拳击?

Does bar (or any function taking a non-generic interface) means there will be boxing?

确实(或任何功能承担类型的通用接口)意味着将有拳击?

Does foo (or any function taking a generic interface on the type) means there will be boxing?

感谢。

推荐答案

任何时候,一个结构被转换为一个接口,它是盒装。 T> IComparable的1所述的目的;是让这样的事情:

Any time a struct is cast to an interface, it is boxed. The purpose of IComparable<T> is to allow for something like:

void bar<T>(T value) where T : IComparable<T> { /* etc. */ }

在该方式使用,该结构将被作为传递结构(通过一般类型参数),而不是作为一个接口,并因此将不必被装箱。注意,取决于结构的大小,有时可能是更好的由值,有时作为参考,以通虽然当然,如果一个是使用像IComparable的一种的现有接口必须通过作为接口的需求。

When used in that fashion, the struct will be passed as a struct (via the generic type parameter) rather than as an interface, and thus will not have to be boxed. Note that depending upon the size of the struct, it may sometimes be better to pass by value and sometimes by reference, though of course if one is using an existing interface like IComparable one must pass as the interface demands.

这篇关于铸造结构成一个通用的接口时,是否有拳击/拆箱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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