强制 REAL 不可为空的字符串引用类型

Jér*_*VEL 5 c# string .net-core c#-8.0 nullable-reference-types

我刚刚尝试了新的C# 8 Nullable Reference Type,它允许我们使用不可为空的字符串。

在我的.csproj(.NET Core 3.1) 中,我设置了这个:

<Nullable>enable</Nullable>
Run Code Online (Sandbox Code Playgroud)

我创建了一个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; }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我故意在我的类中创建一个Main()带有null值的新实例时:

var test = new FooClass(testString:null, testDate:null);
Run Code Online (Sandbox Code Playgroud)

编译器对testString参数没问题,但testDate它告诉我参数:

参数 2:无法从“ <null>”转换为“ DateTime

如何为第一个参数获得相同的行为?

我的testString参数是一个不可为空的引用类型,就像testDate. 由于我没有将其声明为string?,因此我希望编译器对这两个参数的行为方式相同。

是否有另一个功能可以激活以在 C# 中强制执行真正的不可为空的字符串?

Pav*_*ski 5

您可以将TreatWarningsAsErrors选项添加到您的csproj文件中

<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
Run Code Online (Sandbox Code Playgroud)

或将CS8625警告添加到WarningsAsErrors列表中

<WarningsAsErrors>NU1605;CS8625</WarningsAsErrors>
Run Code Online (Sandbox Code Playgroud)

这段代码会产生一个预期的错误

<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
Run Code Online (Sandbox Code Playgroud)

错误 CS8625:无法将 null 文字转换为不可为 null 的引用类型。

testDate可空引用类型在 CLR 中作为类型注释实现,这可能是编译器首先在原始示例中显示错误的原因。

<WarningsAsErrors>NU1605;CS8625</WarningsAsErrors>
Run Code Online (Sandbox Code Playgroud)

当您消除此错误时,您将看到带有可为空引用错误/警告的预期行为