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

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

    You can use ReferenceType transparently as if float, int etc. were actually reference types if you add a conversion operator to the class:

    class ReferenceType where T : struct
    {
        public T Value { get; set; }
        public ReferenceType(T value) { this.Value = value; }
        public static implicit operator ReferenceType(T b)
        {
            ReferenceType r = new ReferenceType(b);
            return r;
        }
        public static implicit operator T(ReferenceType b)
        {
            return b.Value;
        }
    }
    ReferenceType f1 = new ReferenceType(100f);
    f1 = 200f;
    float f2 = f1;
    

    By using the explicit qualifier instead of implicit, you can require casts for these conversions, if you want to make things clearer at the expense of a little verbosity.

提交回复
热议问题