在确保T实际上是整数之后,我试图将泛型类型参数T值的值转换为整数:
public class Test
{
void DoSomething<T>(T value)
{
var type = typeof(T);
if (type == typeof(int))
{
int x = (int)value; // Error 167 Cannot convert type 'T' to 'int'
int y = (int)(object)value; // works though boxing and unboxing
}
}
}
Run Code Online (Sandbox Code Playgroud)
虽然它通过装箱和拆箱工作,但这是一个额外的性能开销,如果有办法直接进行,我就会徘徊.