C#: Array of references / pointers to a number of integers

前端 未结 6 1277
梦毁少年i
梦毁少年i 2020-12-19 23:19

I would like to hold references to a number of shorts in an array. I assumed I could just create the shorts and then add them to the array. So... every time the referenced o

6条回答
  •  离开以前
    2020-12-19 23:50

    The short type is a value type and does not work like reference types which behaves like you are expecting your shorts to behave. When you assign a value type to a variable, its value is assigned, not its reference. vs[0] will hold a copy of the value you assigned to v1.

    If you really need to have the values in the array change when you change the original value, you need to wrap your short in a reference type. Here is an example:

    public class ShortHolder {
      public short Value { get; set; }
    }
    

    Then you can use it like this:

    var v1 = new ShortHolder() { Value=123; }
    var shortArray = new ShortHolder[1];
    shortArray[0] = v1;
    

    If you change v1.Value, then shortArray[0].Value will also change.

提交回复
热议问题