C# generics: cast generic type to value type

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

    Well, it strikes me that the type really isn't properly generic to start with: it can only be one of a few types, and you can't express that constraint.

    Then you want to call a different overload of GetBytes based on the type of T. Generics doesn't work well for that sort of thing. You could use dynamic typing to achieve it, in .NET 4 and above:

    public byte[] GetBytes()
    {
        return BitConverter.GetBytes((dynamic) _value);
    }
    

    ... but again this doesn't really feel like a nice design.

提交回复
热议问题