【问题标题】:Enforce REAL non-nullable string reference type强制执行 REAL 不可为空的字符串引用类型
【发布时间】: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:无法从 '&lt;null&gt;' 转换为 '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


【解决方案1】:

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

<TreatWarningsAsErrors>true</TreatWarningsAsErrors>

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

<WarningsAsErrors>NU1605;CS8625</WarningsAsErrors>

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

var test = new FooClass(testString: null, testDate: default);

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

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

var test = new FooClass(testString: null, testDate: null);

当您摆脱此错误时,您会看到预期的行为以及可空引用错误/警告

【讨论】:

  • 感谢您的回答,这正是我想要的。我没有将所有警告视为错误,而是将此警告添加到现有警告&lt;WarningsAsErrors&gt;NU1605;CS8625&lt;/WarningsAsErrors&gt;
  • @JérômeMEVEL 是的,这也有效。将更新答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-09
  • 1970-01-01
  • 1970-01-01
  • 2015-09-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-08
相关资源
最近更新 更多