如何在不使用C#创建新对象的情况下修改装箱的值? [英] How to modify the boxed value without creating a new object in C#?
问题描述
如何在不使用C#创建新对象的情况下修改装箱的值?
How to modify the boxed value without creating a new object in C#?
例如如果我有object o = 5;
,并且想将装箱的5
的值更改为6
,该怎么办?
E.g. if I have object o = 5;
and I want to change the value of the boxed 5
to 6
, how can I do that?
o = 6;
将在堆上创建一个新对象,并将对该对象的引用分配给o
.还有其他更改框值的方法吗?
The o = 6;
will create a new object on the heap and assign the reference to that object to the o
. Are there any other ways to change the boxed value?
推荐答案
您可以自己进行装箱",而不是对其进行修改.
You can do the "boxing" yourself, than you can modify it.
class Box
{
public int Value { get;set;}
}
这可防止自动装箱.
如果您将自己定义为转换运算符
If you define yourself an conversion operator
public static Box operator(int value) => new Box() { Value = value }
您可以保留与上面相同的语法.但是,此语法将创建一个新对象,如您所见.要修改对象,您必须
You can keep the same syntax as above. But this syntax will create a new object as you see. To modify the object, you would have to
Box b = 5;
object o = b;
((Box)o).Value = 6;
// or
b.Value = 6;
这篇关于如何在不使用C#创建新对象的情况下修改装箱的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!