我尝试了一个简单的记录:
#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;
...
}
我的问题是,这是正确的吗?我对此感到非常惊讶,因为我认为重点是让创建这样的记录变得非常简单,并且必须编写/维护构造函数非常乏味,尤其是在经常更改的大记录上。还是我在这里遗漏了什么?
最佳答案
您似乎在期待自动生成的 Primary Constructor ,但是当您使用 record parameters in the record type declaration 时,它是自动生成的(通常您会获得所有记录的好处)。 ,自动映射到 public get
and init
properties并从主构造函数自动初始化,从而消除 NRT 警告。
这意味着您基本上通过使用添加了 record
的普通构造函数语法来获得所有记录类型的糖。关键词:
public record Product(string Name, int CategoryId, string Phone, Address Address, Manager Manager) { }
关于C# 9.0 记录 - 不可为空的引用类型和构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63424115/