How to modify the boxed value without creating a new object in C#?

那年仲夏 提交于 2020-05-24 05:05:21

问题


How to modify the boxed value without creating a new object in C#?

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?

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?


回答1:


You can do the "boxing" yourself, than you can modify it.

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

This prevents the automatic boxing.

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;


来源:https://stackoverflow.com/questions/58922921/how-to-modify-the-boxed-value-without-creating-a-new-object-in-c

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