如何避免报关时出现CS8618警告?

问题描述 投票:0回答:2

假设以下 C# 代码(并假设 nullable 已启用):

class Foo
{
    public string Bar;
}

var foo = new Foo { Bar = "some value" };

如何避免 CS8618 警告声明 Bar 没有默认值,而是仅在尝试构造 Foo 而不初始化它时收到警告? IE。以上对我来说似乎很好,但以下应该产生警告(可转换为错误):

class Foo
{
    public string Bar;
}

var foo = new Foo { };

因为 Bar 是不可为 null 的字符串,因此不能在不为其提供值的情况下创建 Foo。 我问是因为我要转换为启用可为空的代码库有很多这样的事情。我可以通过为每个这样的属性分配一个默认的虚拟值来解决这个问题,但是编译器不会捕获在没有正确初始化其属性的情况下创建 Foo 的情况。唯一的其他解决方案似乎是为所有此类类编写显式构造函数,但其中一些具有 15 个以上的属性,并且(IMO)它实际上使代码的可读性降低 - 尤其是。因为没有办法强制命名参数,所以像

new TextBox { Color = Color.Red, Width = 15, Height = 20, Title = "My Box", FontFace = "Arial" }
这样的调用可以变成
new TextBox(Color.Red, 15, 20, "Arial", "My Box")
,出于显而易见的原因,这绝对不是可取的。好像应该有更好的办法吧?

c# nullable
2个回答
0
投票

你可以使用下面的null-forgiving赋值-

public string Bar = null!;

0
投票

您可以在 C# 11 中使用

required
修饰符。

class Foo
{
    public required string Bar; // no nullability warnings
}

var foo = new Foo { Bar = "some value" };

var foo2 = new Foo { }; // won't compile
© www.soinside.com 2019 - 2024. All rights reserved.