C# generics: cast generic type to value type

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

    I am on the side that this is an interesting real life problem that has nothing to do with "bad" design but rather standard C# limitations. Casting through object

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

    or, in the current language as

    if (this._value is int intValue)
    {
        return BitConverter.GetBytes(intValue);
    } 
    

    works but causes a performance hit due to ValueType boxing.

    The solution to this problem is Unsafe.As() from System.Runtime.CompilerServices.Unsafe NuGet package:

    if(typeof(T) == typeof(int))
    {
         return BitConverter.GetBytes(Unsafe.As(ref this._value));
    }
    

    Results in no explicit or implicit cast to object.

提交回复
热议问题