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

前端 未结 6 1276
梦毁少年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:43

    Short is a value type, but you're trying to make it behave like a reference type.

    You can create a class with a short property and then use an array of that class:

    public class MyShort
    {
        public short Value {get; set;}
    }
    
    public class SomeOtherClass
    {
       public void SomeMethod()
       {
           MyShort[] array = new MyShort[2];
           array[0] = new MyShort {Value = 5};
           array[1] = new MyShort {Value = 2};
    
           array[0].Value = 3;
       }
    }
    

    There's potentially some work you can do there to make it smoother (like implementing a converter from short to your wrapper class and back).

提交回复
热议问题