C# 9.0 记录 - 不可为 null 的引用类型和构造函数

C# 9.0 records - non-nullable reference types and constructor

我尝试了简单的记录:

#nullable enable

public record Product
{
    public readonly string Name;
    public readonly int CategoryId;
    public readonly string Phone;
    public readonly Address Address;
    public readonly Manager Manager;
}

我收到警告:

Non-nullable property 'Name' is uninitialized. Consider declaring the property as nullable.

(same for all fields except CategoryId)

基本上,如果我理解正确,接受和设置所有字段的构造函数 不是 由编译器自动生成并且(使用 #nullable enable 时)我必须自己写,即:

public Product(string Name, int CategoryId, string Phone, Address Address, Manager Manager) {
  this.Name=Name;
  this.CategoryId=CategoryId;
   ...
}

我的问题是,这是正确的吗?我对此感到非常惊讶,因为我认为重点是让创建这样的记录变得非常简单,并且必须 write/maintain 构造函数非常乏味,尤其是在经常变化的大记录上。 或者我在这里遗漏了什么?

您似乎期待 auto-generated Primary Constructor, but it is auto-generated (and in general you get all the record benefits) when you utilize the record parameters in the record type declaration, which are automatically mapped to public get and init properties 并从主构造函数自动初始化,从而消除了 NRT 警告。

这意味着您基本上使用添加了 record 关键字的普通构造函数语法来获得所有记录类型糖:

public record Product(string Name, int CategoryId, string Phone, Address Address, Manager Manager) { }