【发布时间】:2020-01-27 09:44:45
【问题描述】:
我刚刚尝试了新的C# 8 Nullable Reference Type,它允许我们使用不可为空的字符串。
在我的.csproj (.NET Core 3.1) 我设置了这个:
<Nullable>enable</Nullable>
我创建了一个FooClass,如下:
public class FooClass
{
public FooClass(string testString, DateTime testDate)
{
if (testString == null || testString == string.Empty)
throw new ArgumentNullException(nameof(testString));
else if (testDate == null)
throw new ArgumentNullException(nameof(testDate));
MyString = testString;
MyDate = testDate;
}
public string MyString { get; }
public DateTime MyDate { get; }
}
但是,当我在我的 Main() 中创建我的类的新实例时,故意使用 null 值:
var test = new FooClass(testString:null, testDate:null);
编译器可以使用testString 参数,但是使用testDate 参数它告诉我:
参数 2:无法从 '
<null>' 转换为 'DateTime'
我怎样才能为第一个参数获得相同的行为?
我的testString 参数是不可为空的引用类型,就像testDate 一样。由于我没有将其声明为 string?,因此我希望编译器对两个参数的行为方式相同。
是否有另一个功能可以激活以在 C# 中强制执行 real 不可为空的字符串?
【问题讨论】:
-
“编译器很好” - 你应该得到一个编译器警告。会这样吗?
-
warning CS8625: Cannot convert null literal to non-nullable reference type.它显示了这一点(在您从testdate中删除null之后)。您可以在此处以错误形式威胁警告以获取编译错误 -
您能否验证您是否收到有关
testString的警告消息? -
只有在将
DateTime对象提供给我的testString参数后,我才收到警告消息。如果我给它null,则警告消息不会出现
标签: c# string .net-core c#-8.0 nullable-reference-types