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

标签 c# c#-9.0

我尝试了一个简单的记录:

#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/

相关文章:

C# 9 新的 "nested switch expression"与关系模式

C# 9 - 使用 Entity Framework 更新记录的仅初始化属性

ssl - 如何通过代码将现有的 SSL 证书分配给新的 IIS 站点?

c# - lambda 中的 SQL 'IN' 运算符

c# - 读取文件的特定字节

c# - 用户控件内的 TextBox textchange 事件

c# - 在 C#9 中,仅初始化属性与只读属性有何不同?

c# - 记录类型 : overriding EqualityContract breaks the equality/hashcode match

c# - 清除 mdf 数据库时自动递增的主键

c# - Silverlight 中的对象深拷贝