C# generics: cast generic type to value type

前端 未结 8 2562
佛祖请我去吃肉
佛祖请我去吃肉 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:24

    Pretty late answer, but anyways... there is a way to make it slightly nicer... Make use of generics in a this way: Implement another generic type which converts the types for you. So you don't have to care about unboxing, casting etc of the type to object... it will just work.

    Also, in your GenericClass, now you don't have to switch the types, you can just use IValueConverter and also cast it as IValueConverter. This way, generics will do the magic for you to find the correct interface implementation, and in addition, the object will be null if T is something you do not support...

    interface IValueConverter where T : struct
    {
        byte[] FromValue(T value);
    }
    
    class ValueConverter:
        IValueConverter,
        IValueConverter,
        IValueConverter
    {
        byte[] IValueConverter.FromValue(int value)
        {
            return BitConverter.GetBytes(value);
        }
    
        byte[] IValueConverter.FromValue(double value)
        {
            return BitConverter.GetBytes(value);
        }
    
        byte[] IValueConverter.FromValue(float value)
        {
            return BitConverter.GetBytes(value);
        }
    }
    
    public class GenericClass where T : struct
    {
        T _value;
    
        IValueConverter converter = new ValueConverter() as IValueConverter;
    
        public void SetValue(T value)
        {
            this._value = value;
        }
    
        public byte[] GetBytes()
        {
            if (converter == null)
            {
                throw new InvalidOperationException("Unsuported type");
            }
    
            return converter.FromValue(this._value);
        }
    }
    

提交回复
热议问题