繁体   English   中英

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

[英]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;
}

我收到警告:

不可为空的属性“名称”未初始化。 考虑将属性声明为可为空。

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

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

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

您似乎期待自动生成的Primary Constructor ,但是当您使用记录类型声明中的记录参数时,它是自动生成的(通常您会获得所有记录的好处),这些参数会自动映射到公共getinit属性并从主构造函数自动初始化,从而消除 NRT 警告。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM