與非預設建構函式一起使用

你可以將物件初始值設定項與建構函式結合使用,以在必要時初始化型別以一個如此定義的類為例:

public class Book {
    public string Title { get; set; }
    public string Author { get; set; }

    public Book(int id) {
        //do things
    }

    // the rest of class definition
}

var someBook = new Book(16) { Title = "Don Quixote", Author = "Miguel de Cervantes" }

這將首先使用 Book(int) 建構函式例項化 Book,然後在初始化程式中設定每個屬性。它相當於:

var someBook = new Book(16);
someBook.Title = "Don Quixote";
someBook.Author = "Miguel de Cervantes";