C# generics: cast generic type to value type

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

    First off, this is a really bad code smell. Any time you're doing a type test on a type parameter like this odds are good you're abusing generics.

    The C# compiler knows that you are abusing generics in this way and disallows the cast from the value of type T to int, etc. You can turn off the compiler getting in your way by casting the value to object before you cast it to int:

    return BitConverter.GetBytes((int)(object)this._value);
    

    Yuck. Again, it would be better to find another way to do this. For example:

    public class NumericValue
    {
        double value;
        enum SerializationType { Int, UInt, Double, Float };
        SerializationType serializationType;        
    
        public void SetValue(int value)
        {
            this.value = value;
            this.serializationType = SerializationType.Int
        }
        ... etc ...
    
        public byte[] GetBytes()
        {
            switch(this.serializationType)
            {
                case SerializationType.Int:
                    return BitConverter.GetBytes((int)this.value);
                ... etc ...
    

    No generics necessary. Reserve generics for situations that are actually generic. If you've written the code four times one for each kind of type, you haven't gained anything with generics.

提交回复
热议问题