在 C# 中将字节数组转换为泛型类型值
Convert byte array to generic type value in C#
我想要一个将字节数组转换为泛型类型值的辅助方法:
public static T BytesToValue<T>(byte[] bytes)
{
int pos = 0;
T result = default;
foreach (byte b in bytes)
{
//Cannot convert from type byte to T error here
result |= ((T)b) << pos;
pos += 8;
}
return result;
}
问题是编译器报错
该方法将主要用于获取 int 和 long 值,性能非常关键。
如何解决这个问题?
按位运算符不能用于泛型类型参数。
即使这个简单的转换也无法编译:
result = (T)b;
但是我们可以编写这样的编译器(对其他情况有用):
result = (T)Convert.ChangeType(b, typeof(T));
所以这不会编译:
result |= ( (T)Convert.ChangeType(b, typeof(T)) ) << pos;
我想要一个将字节数组转换为泛型类型值的辅助方法:
public static T BytesToValue<T>(byte[] bytes)
{
int pos = 0;
T result = default;
foreach (byte b in bytes)
{
//Cannot convert from type byte to T error here
result |= ((T)b) << pos;
pos += 8;
}
return result;
}
问题是编译器报错
该方法将主要用于获取 int 和 long 值,性能非常关键。
如何解决这个问题?
按位运算符不能用于泛型类型参数。
即使这个简单的转换也无法编译:
result = (T)b;
但是我们可以编写这样的编译器(对其他情况有用):
result = (T)Convert.ChangeType(b, typeof(T));
所以这不会编译:
result |= ( (T)Convert.ChangeType(b, typeof(T)) ) << pos;