[英]C# 9.0 records - non-nullable reference types and constructor
I tried just a simple record:我尝试了一个简单的记录:
#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;
}
I get warnings:我收到警告:
Non-nullable property 'Name' is uninitialized.
不可为空的属性“名称”未初始化。 Consider declaring the property as nullable.
考虑将属性声明为可为空。
(same for all fields except CategoryId)
(对于除 CategoryId 之外的所有字段都相同)
Basically, if I understand correctly, a constructor accepting and setting all fields is not auto-generated by the compiler and (when using #nullable enable
) I have to write it myself, ie:基本上,如果我理解正确,编译器不会自动生成接受和设置所有字段的构造函数,并且(使用
#nullable enable
时)我必须自己编写它,即:
public Product(string Name, int CategoryId, string Phone, Address Address, Manager Manager) {
this.Name=Name;
this.CategoryId=CategoryId;
...
}
My question is, is this correct?我的问题是,这是正确的吗? I am very surprised by this as I thought the whole point was to make creating records like that really simple, and having to write/maintain the constructor is very tedious, especially on big records that change often.
我对此感到非常惊讶,因为我认为重点是让创建这样的记录变得非常简单,并且必须编写/维护构造函数非常乏味,尤其是在经常更改的大记录上。 Or am I missing something here?
或者我在这里错过了什么?
You seem to be expecting the 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 and automatically initialized from the primary constructor, thus eliminating the NRT warning.您似乎期待自动生成的Primary Constructor ,但是当您使用记录类型声明中的记录参数时,它是自动生成的(通常您会获得所有记录的好处),这些参数会自动映射到公共
get
和init
属性并从主构造函数自动初始化,从而消除 NRT 警告。
Which means that you get all record type sugar by basically using the normal constructor syntax with added record
keyword:这意味着您基本上通过使用添加了
record
关键字的普通构造函数语法来获得所有记录类型糖:
public record Product(string Name, int CategoryId, string Phone, Address Address, Manager Manager) { }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.