Does unboxing occur when a class's value-type member is referenced?

元气小坏坏 提交于 2020-01-01 05:22:09

问题


I read What is boxing and unboxing and what are the trade offs? but can't understand one thing. Suppose I have a class:

class MyClass
{
    public int Value { get; set; }
}

And I want to get value within my method:

void MyFunc(MyClass cls)
{
    int i = cls.Value;
}

As a class placed in heap, I guess that Value placed in a heap too? And therefore operation

int i = cls.Value;

is unboxing? Or it's not unboxing?


回答1:


Stop thinking about stack and heap; that's completely the wrong way to think about it. It is emphatically not the case that "boxed" means "on the heap", and therefore anything "on the heap" must be "boxed".

Stack and heap are irrelevant. Rather, think about references and values. A value of value type is boxed when it must be treated as a reference to an object. If you need to have a reference to a value of a value type, you make a box, put the value in the box, and make a reference to the box. And there, now you have a reference to a value of value type.

Do not confuse that with making a reference to a variable of value type; that is completely different. A variable and a value are two very different things; to make a reference to a variable you use the "ref" keyword.




回答2:


Boxing or unboxing doesn't have anything to do with storing values on heap or stack. You should read the article "Boxing and Unboxing" from the C# Programming Guide. In your example none of these two occurs because you're assigning int to int.




回答3:


It's neither unboxing nor boxing. Considering you assign to int without cast and, I hope, this code compiles, that means that cls.Value is a Integer(int) type. So assign int to int. What happens here is a value copy.




回答4:


int i = 5;
object o = i;   // boxing of int i
int i = (int)o; // unboxing of object o

Note that we do not assign i to a field or property of an object, but to the object itself. It is comparable to the nature of light. Light can be perceived of being made of particles (photons) or being a wave. An int can be an int object (a reference type) or an int value type. You can however not define an int to be a reference type directly; you must convert it to an object, e.g. by assigning it to a variable, parameter or property of type object or casting it to object to make it a reference type.



来源:https://stackoverflow.com/questions/8809959/does-unboxing-occur-when-a-classs-value-type-member-is-referenced

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