此代码无法编译:
public static void f<T>()
{
T? a = null;
}
错误
Cannot convert 'null' to type parameter 'T' because it could be a value type. Consider using 'default(T)' instead
为什么会这样?
此代码无法编译:
public static void f<T>()
{
T? a = null;
}
错误
Cannot convert 'null' to type parameter 'T' because it could be a value type. Consider using 'default(T)' instead
为什么会这样?
或者
对于引用类型,
default它总是null.顺便说一下,对于引用类型,
T?这只是一个注解,实际上在运行string时string?是一样的。对于有意义的,int?它是Nullable<int>,所以如果你声明T?它而不对其应用任何限制,编译器会发疯。尽管从语言语义的角度来看,一切似乎都应该合乎逻辑。您可以在文档中阅读有关所有细微差别的更多信息:可为空的引用类型。