允許在建構子呼叫後,直接以大括號設定屬性/欄位:
public class Test1
{
public string String1 { get; set; }
public int Int1;
public Test1() { }
public Test1(int i) { Int1 = i; }
}
// 用法
var t0 = new Test1 { String1 = "https://xianfen.Net", Int1 = 0 };
var t1 = new Test1(0) { String1 = "https://xianfen.Net" }; // 先呼叫建構子,再設定屬性
IL 機制:先呼叫無參建構子(或指定建構子),再依序呼叫屬性 set 或設定公共欄位。因此類別必須有無參建構子(或明確呼叫有參建構子)。
為實作 IEnumerable 且具 Add 方法的集合提供宣告式初始化:
List<Test1> list = new List<Test1>
{
new Test1 { String1 = "https://xianfen.Net", Int1 = 0 },
new Test1 { String1 = "https://www.xianfen.Net", Int1 = 1 },
new Test1 { String1 = "https://www.bianceng.cn", Int1 = 2 }
};
IL 實作:編譯器產生暫存區域變數,逐一 Add 進集合。
var t3 = new { String1 = "https://xianfen.Net", Int1 = 0 };
特徵:
<>f__AnonymousType0`2[System.String,System.Int32]get)Equals/GetHashCode/ToString,以屬性值為基準object 或 dynamic)select new { ... })中極具價值物件/集合初始化器大幅減少樣板代碼;匿名型別雖有限制,但在 LINQ 臨時資料投影場景無可替代。理解其 IL 實作有助於避開陷阱(如建構子需求、不可變性)。