此代码无法编译:
public T Get<T>()
{
T result = default(T);
if(typeof(T) == typeof(int))
{
int i = 0;
result = (T)i;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
但是,这段代码确实编译:
public T Get<T>()
{
T result = default(T);
if(typeof(T) == typeof(int))
{
int i = 0;
result = (T)(object)i;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
代码也可以正常工作.我不明白为什么编译器可以将对象(实际类型可以是任何东西)强制转换为T,但是不能将int(从对象中转换为对象)转换为T.