c# - 如何告诉编译器必须初始化属性

标签 c# initialization c#-9.0 non-nullable

我有一个类,例如这个:

public class Foo
{
    public string Bar { get; init; }
    public IImmutableSet<int> Baz { get; init; }
}

当我这样写的时候,我得到一个编译器警告

Non-nullable property 'Bar' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. csharp(CS8618)

有很多内容解决这个问题(例如 here ),但据我所知,它只是关于如何通过设置默认值或使用 "假默认值”,如 null!

但在我的例子中,默认值没有意义。 相反,我想告诉编译器必须显式设置这些属性,这样如果在使用对象之前没有设置任何属性,编译器就会提示。就像未分配的局部变量的情况一样:

enter image description here

这可能吗?如果可能,怎么做?

我知道我可以只定义一个带参数的构造函数,因此使用该构造函数是创建新实例的唯一方法。但是因为我有很多像上面这样的类,我需要写很多额外的代码(即构造函数)。如果有一种“必须初始化”标志,我的代码的读者也会更清楚。

最佳答案

我认为 get; 只有带有构造函数的属性才是可行的方法。

public class C
{
    public C(string a)
    {
        A = a;
    }

    public string A { get; }
}

I would need to write quite of lot of extra code (i.e. the constructors).

如今创建构造函数非常容易。它需要:

  • Ctrl+. + 在 VS Code 中单击鼠标 1 次:

    enter image description here

  • Ctrl+. + 向下箭头 + 在 VS 中输入:

    enter image description here


微软怎么说?

1。 Working with Nullable Reference Types

Working with Nullable Reference Types不可为空的属性和初始化中显示了 3 个选项:

一个。构造函数

Constructor binding is a useful technique to ensure that your non-nullable properties are initialized:

b。可为空的支持字段

Unfortunately, in some scenarios constructor binding isn't an option; navigation properties, for example, cannot be initialized in this way. (...) One way to deal with these scenarios, is to have a non-nullable property with a nullable backing field: C#

private Address? _shippingAddress;

public Address ShippingAddress
{
    set => _shippingAddress = value;
    get => _shippingAddress
           ?? throw new InvalidOperationException("Uninitialized property: " + > nameof(ShippingAddress));
}

c。强制初始化为 null!

作为一种更简洁的替代方法,可以借助允许空值的运算符 (!) 将属性简单地初始化为空值:

C#

public Product Product { get; set; } = null!;

An actual null value will never be observed except as a result of a programming bug, e.g. accessing the navigation property without properly loading the related entity beforehand.

2。 Learn techniques to resolve nullable warnings

Learn techniques to resolve nullable warnings再次没有 get 的例子; init; 属性,文章提出了两个处理警告的选项:

  • 构造器
  • 初始化为 null!;

    to indicate that a member is initialized in other code.

3。 Attributes for null-state static analysis interpreted by the C# compiler

对于更复杂的场景,可能值得一看 Attributes for null-state static analysis interpreted by the C# compiler并使用一些可用的属性。不过,我认为这不是日常代码的路径。

关于c# - 如何告诉编译器必须初始化属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71288394/

相关文章:

c# - 有没有办法创建一个随着树的修改而更新的 Linq XElement 迭代器?

java - 如何使用其中的条目/值初始化 LinkedList?

c# - 禁用特定的C#9源生成器

C# 9.0 With 表达式。如何使用它们?

c# - 检查字符前后是否有空格进行字符串拆分

c# - Message Queue 服务不可用

c# - 从 web 服务下载文件 - 在 ASP.NET 站点中

c++ - (重新)将 vector 初始化为具有初始值的特定长度

java - 创建一个二维数组并将每个元素初始化为 i * j 的值,其中 i 和 j 是 2 个索引(例如,元素 [5][3] 为 5 * 3 = 15)

c#-9.0 - 使用 C#9 记录添加注释的正确方法是什么?