如何使 [DisallowNull] 显示对象初始值设定项的错误?

How to make [DisallowNull] show an error for an object initializer?

.Net Core 允许你用 [DisallowNull] 修饰 属性 来告诉编译器不允许代码将 属性 设置为空,即使 属性 本身被声明为允许它。例如:

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.
};

有没有办法让上面的代码引起编译器warning/error?

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

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

这警告说 Text 有一个默认值 null(因此需要用 = null! 来抑制它),但除此之外似乎做你想做的。

SharpLab