如果需要,可以将对象初始值设定项与构造函数结合使用以初始化类型。例如,定义一个这样的类:
public class Book { public string Title { get; set; } public string Author { get; set; } public Book(int id) { //做事 } // 其余的类定义 } var someBook = new Book(16) { Title = "Don Quixote", Author = "Miguel de Cervantes" }
这将首先Book用Book(int)构造函数实例化a ,然后在初始化程序中设置每个属性。它等效于:
var someBook = new Book(16); someBook.Title = "Don Quixote"; someBook.Author = "Miguel de Cervantes";