与非默认构造函数一起使用

你可以将对象初始值设定项与构造函数结合使用,以在必要时初始化类型以一个如此定义的类为例:

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";