我有一个通用的类可以保存指定类型T的值.
该值可以是int,uint,double或float.
现在我想得到值的字节来将其编码成一个特定的协议.
因此,我想使用BitConverter.GetBytes()方法,但不幸的是Bitconverter不支持泛型类型或未定义的对象.这就是为什么我要转换该值并调用GetBytes()的特定重载.
我的问题:
如何将泛型值转换为int,double或float?
这不行:
该值可以是int,uint,double或float.
现在我想得到值的字节来将其编码成一个特定的协议.
因此,我想使用BitConverter.GetBytes()方法,但不幸的是Bitconverter不支持泛型类型或未定义的对象.这就是为什么我要转换该值并调用GetBytes()的特定重载.
我的问题:
如何将泛型值转换为int,double或float?
这不行:
- public class GenericClass<T>
- where T : struct
- {
- T _value;
- public void SetValue(T value)
- {
- this._value = value;
- }
- public byte[] GetBytes()
- {
- //int x = (int)this._value;
- if(typeof(T) == typeof(int))
- {
- return BitConverter.GetBytes((int)this._value);
- }
- else if (typeof(T) == typeof(double))
- {
- return BitConverter.GetBytes((double)this._value);
- }
- else if (typeof(T) == typeof(float))
- {
- return BitConverter.GetBytes((float)this._value);
- }
- }
- }
是否有可能投出一般的价值?
还是有另一种方式来获取字节?
解决方法
首先,这是一个非常糟糕的代码气味.任何时候,您对类型参数进行类型测试,像这样可能性很好,你滥用泛型.
C#编译器知道你以这种方式滥用泛型,并且不允许将类型为T的值转换为int等.您可以通过在将其转换为int之前将值转换为对象来关闭编译器:
- return BitConverter.GetBytes((int)(object)this._value);
呸.再次,找到另一种方法来做到这一点会更好.例如:
- 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 ...