我想编写通用类,旨在与 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;
}
}
我认为,如果在计算循环中使用此类转换,它们可能会显着降低性能。是否有更好的方法来进行这些转化?
最佳答案
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;
}
}
准备_getInt = x => (T)x
在静态构造函数中为您提供并稍后使用它来转换 int
至 T
.
关于c# - 将泛型参数转换为整数或从整数转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18182285/