.net 5 問世之後,C# 9出了新機制 Record。它介於Reference (參考)Type和Value Type之間。它適合用來儲存data(類似struct)數據,但也保有Reference Type特性如繼承和封裝。因此我們可以用Record來儲存DTO物件。本篇文章就探索Record特性。

Employee繼承Person Record

C# 9 新機制在new record時填寫new即可。以上程式碼顯示如何使用record。Person只包含data,功能類似Struct。而Employee包含Person屬性(Name和Age)。Employee繼承Person。因此我們可以用Person和Employee分別用record代替class類別和struct。
輸出結果如下

Record類型變數比較時是用value類型比較的,因此Person josh和joshSecond的屬性值皆相同,所以比較結果(=)為true相同。但record是Reference Type(參考類型),所以用object.ReferenceEquals比較兩者會回傳False。

ToString()輸出結果呢?

他的輸出結果為

with-expression
當我們想改變record欄位值時候,你會發現無法改變(imuutable)因為record是不可變的。

這時可以用with-expression

以往我都使用struct來儲存資料因它較少占用記憶體空間(與class相比),但struct不是class所以在一些場景我們會考慮究竟要用class或struct來定義數據類別。Record的問世解決了這問題,讓開發者多了一個合適的選擇。