C# generics: cast generic type to value type

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

    If your only goal is to add the GetBytes method to these types, isn't it a much nicer solution to add them as extension methods like so:

    public static class MyExtensions {
        public static byte[] GetBytes(this int value) {
            return BitConverter.GetBytes(value) ;
        }
        public static byte[] GetBytes(this uint value) {
            return BitConverter.GetBytes(value) ;
        }
        public static byte[] GetBytes(this double value) {
            return BitConverter.GetBytes(value) ;
        }
        public static byte[] GetBytes(this float value) {
            return BitConverter.GetBytes(value) ;
        }
    }
    

    If you really need you generic class for other purposes, just do the dirty "double typecast" like Eric mentioned where you typecast value to object first.

    0 讨论(0)
  • 2021-02-19 04:38

    What would GenericClass<DateTime> 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<T>
    {
        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<int>
    {
        protected override byte[] GetBytesInternal(int value)
        {
            return BitConverter.GetBytes(value);
        }
    }
    
    public class DoubleClass : GenericClass<double>
    {
        protected override byte[] GetBytesInternal(double value)
        {
            return BitConverter.GetBytes(value);
        }
    }
    
    public class FloatClass : GenericClass<float>
    {
        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<T> and provide an appropriate implementation of GetBytes.

    0 讨论(0)
提交回复
热议问题