C# generics: cast generic type to value type

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

提交回复
热议问题