拳击..我做对了吗?
可能的重复:
什么是装箱和拆箱以及交易是什么折扣?
嗨, 据我了解: 当我将值类型的数据分配给(引用)类型对象变量时,它会被装箱,并且结果不是实际引用,因为它指向存储在堆上的值的副本。是这样吗? 谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
嗯,不完全是这样。 (我一开始就误读了你的文章。)
结果是一个真正的参考 - 但它并不引用你的原始变量。它指的是堆上的一个对象,其中包含发生装箱时变量所保存的值的副本。特别是,更改变量的值不会更改框中的值:
C# 不允许您直接访问框中的值 - 您只能通过拆箱并获取副本来获取它。另一方面,C++/CLI 允许单独访问甚至更改框中的值。 (您仍然可以使用 C# 更改框中的值 - 例如,如果值类型实现某个接口,并且接口方法会改变该值。)
通常,导致装箱的引用类型是“对象”,但也可能是某个接口值类型实现,或者只是
System.ValueType
。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:
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
.这可能对你有帮助
This might help you
是的,对于第一部分,将值类型分配给引用变量将使用装箱。
基本上,在任何需要引用类型的上下文中使用值类型都会对值进行装箱。
是的,(在当前的实现中)装箱操作会将值类型复制到堆,并返回对该位置的引用,即使该值已经在堆上(例如对象的值类型属性),所以您不会获得对原始值变量的引用,但这无论如何都是一个实现细节,因为值类型应该被视为不可变。
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.