难道当一个类的价值型构件被引用拆箱发生的? [英] Does unboxing occur when a class's value-type member is referenced?

查看:74
本文介绍了难道当一个类的价值型构件被引用拆箱发生的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读的什么是装箱和拆箱,什么是权衡?但不能明白一件事。假设我有一个类:

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?

推荐答案

停止思考的的和的的;这是完全考虑了错误的方式。它强调的的说:堆,盒装的意思,因此,任何堆必须盒装的情况。

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.

这篇关于难道当一个类的价值型构件被引用拆箱发生的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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