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

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

    Value types are called value types because they are passed by value when passed to methods or assigned via the = operator.

    Another (and more correct) way to look at it is that shorts, ints, etc. are immutable => they cannot be changed. So you basically cannot change a short. If you need an object of type short to change somewhere you need to create a class to hold this object like this:

    
    public class ShortWrapper
    {
        public short ShortValue {get; set;}
    }
    class Program
    {
        static void Main(string[] args)
        {
            ShortWrapper short1 = new ShortWrapper{ ShortValue = 1};
            ShortWrapper short2 = new ShortWrapper { ShortValue = 2 };
    
            ShortWrapper[] shorts = new ShortWrapper[] { short1, short2 };
            shorts[0].ShortValue = 5;
    
            Console.WriteLine(short1.ShortValue);
        }
    }
    
    

    Essentially the code is replacing the object of type short with a new object.

    BTW chances are that there is something wrong with your design if you need to wrap a naked short. You either should be using some more complex object already or should be working with the array of shorts in some other way. But I guess you are just testing.

提交回复
热议问题