Boxing..do I get it right? [duplicate]

社会主义新天地 提交于 2019-12-11 03:09:37

问题


Possible Duplicate:
What is boxing and unboxing and what are the trade offs?

Hi, From my understanding: When I assign data of value type to (reference) type object variable, it gets boxed and the result is not actual reference as it points to copy of the value stored on the heap. Is that right? Thanks


回答1:


Well, not quite. (I misread your post to start with.)

The result is a real reference - but it doesn't refer to your original variable. It refers to an object on the heap which contains a copy of the value your variable held when boxing occurred. In particular, changing the value of your variable doesn't change the value in the box:

int i = 10;
object o = i;
i = 11;
Console.WriteLine(o); // Prints 10, not 11

C# doesn't let you have direct access to the value inside the box - you can only get it by unboxing and taking a copy. C++/CLI, on the other hand, allows the value inside the box to be accessed separately, and even changed. (You can still potentially change the value in a box with C# - for example if the value type implements some interface and the interface methods mutate the value.)

Often the reference type which causes boxing is "object" but it could be some interface the value type implements, or just System.ValueType.




回答2:


This might help you

int i = 1;
object o = i;   // boxing on the heap
int j = (int) o;    // unboxing to the stack



回答3:


Yes for the first part, assigning a value type to a reference variable will use boxing. Basically using a value type in any context where a reference type is required will box the value.

And yes, (in the current implementation) the boxing operation will copy the value type to the heap, and return a reference to that location, even if the value is already on the heap (e.g. a value type property of an object), so you won't get a reference to the original value variable, but that is an implementation detail anyway, as value types should be treated as immutable.



来源:https://stackoverflow.com/questions/4732925/boxing-do-i-get-it-right

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!