對象初始化器讓編譯器自動生成屬性設值代碼,減少硬編碼行數。.NET 類型高度依賴屬性,傳統初始化需多行賦值:
Person person = new Person();
person.FirstName = "Scott";
person.LastName = "Guthrie";
person.Age = 32;
使用 C# 3.0 對象初始化器可簡化為單行:
Person person = new Person { FirstName = "Scott", LastName = "Guthrie", Age = 32 };
編譯器自動生成對應的屬性 setter 調用,語義保持不變。更強大的是,它支援巢狀複雜屬性初始化。假設 Person 有 Address 類型的 Address 屬性:
Person person = new Person {
FirstName = "Scott",
LastName = "Guthrie",
Age = 32,
Address = new Address {
Street = "One Microsoft Way",
City = "Redmond",
State = "WA",
Zip = 98052
}
};
這種聲明式風格讓對象圖構建更直觀,減少樣板代碼,提升可維護性。