在构造函数调用的方法内初始化的不可为空字段

nos*_*tio 13 .net c# non-nullable .net-core nullable-reference-types

我有一些不可为 null 的字段,我想在从构造函数调用的辅助方法中初始化这些字段,以减少构造函数内部的混乱:

private FlowLayoutPanel _flowPanel;
private ComboBox _printersComboBox;
//...

public PrintSettingsView(IServiceProvider serviceProvider, IPrintSettings printSettings)
{
    InitializeComponent();
    PostInitializeComponent(); // this is where _flowPanel etc get initialized
    // ...
}
Run Code Online (Sandbox Code Playgroud)

如何避免类似的警告Non-nullable field '_flowPanel' must contain a non-null value when exiting constructor. Consider declaring the field as nullable

到目前为止我想到的最好的主意是:

public static void Assert([DoesNotReturnIf(false)] bool condition)
{
  if (!condition) throw new InvalidOperationException();
}

public PrintSettingsView(IServiceProvider serviceProvider, IPrintSettings printSettings)
{
    InitializeComponent();
    PostInitializeComponent();

    Assert(_flowPanel != null);
    Assert(_printersComboBox != null);
    //...
}
Run Code Online (Sandbox Code Playgroud)

当有很多田地时,它仍然变得混乱。还有比这更好的事情吗?

这是一个 .NET 6 项目,因此我可以使用最新、最好的项目。

在此输入图像描述

Rik*_*son 11

您有几个选择:

  1. 用于[MemberNotNull]辅助方法。这有点冗长,但应该可行。请参阅/sf/answers/4547086211/
  2. 从辅助方法(可能是元组?)返回值,并将其解构分配到您想要初始化的字段中。


Dre*_*kes 9

另一种选择是将字段声明为:

private FlowLayoutPanel _flowPanel = null!;
private ComboBox _printersComboBox = null!;
Run Code Online (Sandbox Code Playgroud)

这会强制编译器将这些字段视为已初始化,并禁止!显示该值为 null 但该字段不可为 null 的警告。

请注意,添加空赋值不会更改生成的代码。没有运行时影响,只有设计时影响。


小智 0

将它们定义为可空怎么样:

FlowLayoutPanel? _flowPanel;