[英]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 ,但是當您使用記錄類型聲明中的記錄參數時,它是自動生成的(通常您會獲得所有記錄的好處),這些參數會自動映射到公共get
和init
屬性並從主構造函數自動初始化,從而消除 NRT 警告。
這意味着您基本上通過使用添加了record
關鍵字的普通構造函數語法來獲得所有記錄類型糖:
public record Product(string Name, int CategoryId, string Phone, Address Address, Manager Manager) { }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.