装箱和拆箱 [英] Boxing and Unboxing
问题描述
可能重复:
<一href="http://stackoverflow.com/questions/13055/what-is-boxing-and-unboxing-and-what-are-the-trade-offs">What是装箱和拆箱,什么是权衡?
好吧,我明白,当你框和会发生什么的基本概念拆箱。
箱抛出值类型(栈对象)到System.Object中,并将其存储在堆上 拆箱解包该对象上堆持有该值的类型,并抛出回堆栈上,因此它可以被使用。
下面是我不明白:
-
为什么会这样需要做的......具体的现实世界的例子
-
为什么泛型如此高效?他们说,因为仿制药不需要拆箱或箱,ok..I不知道为什么...什么是落后于仿制药
-
为什么仿制药不如让说,其他类型。让我们说,例如其他的收藏品?
因此,所有的一切,我不明白这一点在实际应用中的code条款,然后进一步去它如何使仿制药好?为什么它没有做任何的这使用泛型的时候第一个地方。
-
这需要在白细胞介素的水平,因为在那里进行的比对引用类型(值类型不同的指令
ldfld
VSldflda
,检出dissassembly为调用一个方法someValueType.ToString()
VSsomeReferenceType.ToString()
,你会看到,说明是不同的)。这些指令不兼容,所以,当你需要一个值类型传递给方法作为一个对象,这个值需要被包裹在一个引用类型(拳击)。这是ineficient因为运行时需要复制值类型,然后创建为了一个新的拳击类传递一个值。
-
泛型是速度更快,因为值类型可以存储作为值,而不是引用所以没有拳击是必要的。以
的ArrayList
VS名单,其中,INT&GT;
。如果你想要把1
到的ArrayList
,CLR的需要框INT
,以便它可以存储在一个[对象]
。名单,其中,T&GT;
然而,使用T []
存储列表内容,使列表使用INT [
这意味着1
不需要为了把它在阵列中进行装箱。
Possible Duplicate:
What is boxing and unboxing and what are the trade offs?
Ok I understand the basic concept of what happens when you box and unbox.
Box throws the value type (stack object) into a System.Object and stores it on the heap Unbox unpackages that object on the heap holding that value type and throws it back on the stack so it can be used.
Here is what I don't understand:
Why would this need to be done...specific real-world examples
Why is generics so efficient? They say because Generics doesn't need to unbox or box, ok..I don't get why...what's behind that in generics
Why is generics better than lets say other types. Lets say for example other collections?
so all in all I don't understand this in application in the real world in terms of code and then going further how it makes generics better...why it doesn't have to do any of this in the first place when using Generics.
This needs to be done because at the IL level there are different instructions for value types than for reference types (
ldfld
vsldflda
, checkout the dissassembly for a method that callssomeValueType.ToString()
vssomeReferenceType.ToString()
and you'll see that the instructions are different).These instructions are not compatible so, when you need to pass a value type to a method as an object, that value needs to be wrapped in a reference type (boxing). This is ineficient because the runtime needs to copy the value type and then create a new boxing type in order to pass one value.
Generics are faster because value types can be stored as values and not references so no boxing is needed. Take
ArrayList
vsList<int>
. If you want to put1
into anArrayList
, the CLR needs to box theint
so that it can be stored in aobject[]
.List<T>
however, uses aT[]
to store the list contents so List uses aint[]
which means that1
doesn't need to be boxed in order to put it in the array.
这篇关于装箱和拆箱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!