Ale*_*x F 5 c# generics casting
byte我想编写通用类,旨在与和 等内置类型一起使用ushort。在内部计算中,我需要将泛型类型转换为整数,然后再转换回泛型类型。我找到了编译此类代码的方法,例如:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我认为,如果在计算循环中使用此类转换,则可能会显着降低性能。有没有更好的方法来进行这些转换?
int转换T有点棘手。我想你可以Expression在这里使用类。
Test<T>类应该看起来像这样:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
它_getInt = x => (T)x在静态构造函数中为您做好准备,并在稍后使用它来转换int为T.