【问题标题】:How to make [DisallowNull] show an error for an object initializer?如何使 [DisallowNull] 显示对象初始化程序的错误?
【发布时间】:2020-01-13 10:38:41
【问题描述】:

.Net Core 允许您使用[DisallowNull] 来装饰属性,以告诉编译器不允许代码将属性设置为 null,即使属性本身已声明允许这样做。例如:

public sealed class Test
{
    [DisallowNull] public string? Text { get; set; }
}

当您尝试将属性显式设置为 null 时,这可以正常工作:

var test = new Test();
test.Text = null; // Warning: "Cannot convert null literal to non-nullable reference type".

但是,如果你使用对象初始化器,它就不起作用:

var test = new Test
{
    Text = null  // No warning. I want one.
};

有什么办法可以让上面的代码引起编译器警告/错误?

【问题讨论】:

标签: c# .net-core nullable-reference-types


【解决方案1】:

在修复发布之前,您可以通过翻转它来解决此问题:

public sealed class Test
{
    [MaybeNull] public string Text { get; set; } = null!;
}

这警告Text 的默认值为null(因此需要使用= null! 抑制它),但除此之外似乎可以做你想做的事。

SharpLab

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    相关资源
    最近更新 更多