[当我尝试使用csc
(版本= 3.3.1-beta3-19461-02
)编译以下简单C#源文件时,我收到一条错误消息,指出System.String
是non-nullable类型:
using System;
#nullable enable
class Prg {
static void Main() {
//
// Compiler says:
// error CS0453: The type 'string' must be a non-nullable value
// type in order to use it as parameter 'T'
// in the generic type or method 'Nullable<T>'
//
Nullable<String> str = "xyz";
Console.WriteLine(str);
}
}
但是,我可以将System.String
的实例设置为null
值:
using System;
class Prg {
static void Main() {
String str = null;
Console.WriteLine(str);
}
}
我很困惑,因为System.String显然可以为空,但在第一个源代码片段中引起了矛盾的错误消息。
我不知道矛盾在哪里?类型T必须是不可为空的,才能用作:
Nullable<T>
而且您不能使用Nullable<String>
,因为字符串是nullable。