铸造泛型参数,并从整 [英] Casting generic parameter to and from integer
问题描述
我想写其目的是一起工作的泛型类的内置类型,如字节
和 USHORT
。在内部计算,我需要投泛型类型为整数,并返回到泛型类型。我发现方式编译这样的代码,例如:
I want to write generic class which is intended to work with built-in types like byte
and ushort
. In internal computations I need to cast generic type to integer and back to generic type. I found the way to compile such code, for example:
class Test<T> where T : struct, IConvertible
{
public static T TestFunction(T x)
{
int n = Convert.ToInt32(x);
T result = (T)Convert.ChangeType(n, typeof(T));
return result;
}
}
我觉得用这样的转换可能显著降低性能,如果它们在计算循环使用。有没有更好的办法让这些转换?
I think that using such conversions may significantly reduce performance, if they are used in computation loops. Is there a better way to make these conversions?
推荐答案
INT
来 T
转换是有点棘手。我想你可以在这里使用表达式
类。
int
to T
conversion is a bit tricky. I think you could use Expression
class here.
测试< T>
类应该可以看起来像:
Test<T>
class should can look like that:
class Test<T> where T : struct, IConvertible
{
private static Func<int, T> _getInt;
static Test()
{
var param = Expression.Parameter(typeof(int), "x");
UnaryExpression body = Expression.Convert(param, typeof(T));
_getInt = Expression.Lambda<Func<int, T>>(body, param).Compile();
}
public static T TestFunction(T x)
{
int n = Convert.ToInt32(x);
T result = _getInt(n);
return result;
}
}
它准备 _getInt = X = GT; (T)X
并为您在静态构造函数之后使用它,转换 INT
到 T
。
It prepares _getInt = x => (T)x
for you in static constructor and uses it later, to convert int
to T
.
这篇关于铸造泛型参数,并从整的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!