C# generics: cast generic type to value type

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

    You could potentially use Convert.ToInt32(this._value) or (int)((object)this._value). But in general if you find yourself having to check for specific types in a generic method, there's a problem with your design.

    In your case, you probably should consider making an abstract base class, and then derived classes for the types you're going to use:

    public abstract class GenericClass
    where T : struct
    {
        protected T _value;
    
        public void SetValue(T value)
        {
            this._value = value;
        }
    
        public abstract byte[] GetBytes();
    }
    
    public class IntGenericClass: GenericClass
    {
        public override byte[] GetBytes()
        {
            return BitConverter.GetBytes(this._value);
        }
    }
    

提交回复
热议问题