Define “custom” integer-based type?

后端 未结 2 1241
陌清茗
陌清茗 2020-12-08 22:08

I have a program that is interfacing with an external library that, among other things, has an unsigned 12-bit value packed in a larger struct.

This used to be 8 bit

2条回答
  •  暖寄归人
    2020-12-08 22:28

    You should create a struct that overrides the implicit conversion operator:

    struct PackedValue {
        private PackedValue(ushort val) {
             if(val >= (1<<12)) throw new ArgumentOutOfRangeException("val");
             this._value = val;
        }
        private ushort _value;
        public static explicit operator PackedValue(ushort value) {
            return new PackedValue(value);
        }
    
        public static implicit operator ushort(PackedValue me) {
            return me._value;
        }
    }
    

提交回复
热议问题