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

前端 未结 1 1225
一整个雨季
一整个雨季 2021-01-26 06:44

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 t

相关标签:
1条回答
  • 2021-01-26 07:26

    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;
    
    0 讨论(0)
提交回复
热议问题