C# generics: cast generic type to value type

前端 未结 8 2574
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-19 03:51

I have a generic class which saves value for the specified type T. The value can be an int, uint, double or float. Now I want to get the bytes of the value to encode it into an

8条回答
  •  失恋的感觉
    2021-02-19 04:38

    What would GenericClass do? Rather, it seems you have a discrete set of classes which know how to get their bytes, so make an abstract base class that does all of the common work, and then make 3 concrete class which override a method to specify the piece that changes between them:

    public abstract class GenericClass
    {
        private T _value;
    
        public void SetValue(T value)
        {
            _value = value;
        }
    
        public byte[] GetBytes()
        {
            return GetBytesInternal(_value);
        }
    
        protected abstract byte[] GetBytesInternal(T value);
    }
    
    public class IntClass : GenericClass
    {
        protected override byte[] GetBytesInternal(int value)
        {
            return BitConverter.GetBytes(value);
        }
    }
    
    public class DoubleClass : GenericClass
    {
        protected override byte[] GetBytesInternal(double value)
        {
            return BitConverter.GetBytes(value);
        }
    }
    
    public class FloatClass : GenericClass
    {
        protected override byte[] GetBytesInternal(float value)
        {
            return BitConverter.GetBytes(value);
        }
    }
    

    This not only provides clean, strongly-typed implementations of your three known types, but leaves the door open for anyone else to subclass Generic and provide an appropriate implementation of GetBytes.

提交回复
热议问题