C#3.0(.NET 3.5)引入了對(duì)象初始化器語法,這是一種初始化類或集合對(duì)象的新方法。對(duì)象初始化程序允許您在創(chuàng)建對(duì)象時(shí)將值分配給字段或?qū)傩裕鵁o需調(diào)用構(gòu)造函數(shù)。
public class Student { public int StudentID { get; set; } public string StudentName { get; set; } public int Age { get; set; } public string Address { get; set; } } class Program { static void Main(string[] args) { Student std = new Student() { StudentID = 1, StudentName = "Bill", Age = 20, Address = "New York" }; } }
在上面的示例中,沒有任何構(gòu)造函數(shù)的情況下定義了 Student 類。在 Main() 方法中,我們創(chuàng)建了Student對(duì)象,并同時(shí)為大括號(hào)中的所有或某些屬性分配了值。這稱為對(duì)象初始化器語法。
編譯器將上述初始化程序編譯為如下所示的內(nèi)容。
Student __student = new Student(); __student.StudentID = 1; __student.StudentName = "Bill"; __student.Age = 20; __student.StandardID = 10; __student.Address = "Test"; Student std = __student;
可以使用集合初始化器語法以與類對(duì)象相同的方式初始化集合。
var student1 = new Student() { StudentID = 1, StudentName = "John" }; var student2 = new Student() { StudentID = 2, StudentName = "Steve" }; var student3 = new Student() { StudentID = 3, StudentName = "Bill" } ; var student4 = new Student() { StudentID = 3, StudentName = "Bill" }; var student5 = new Student() { StudentID = 5, StudentName = "Ron" }; IList<Student> studentList = new List<Student>() { student1, student2, student3, student4, student5 };
您還可以同時(shí)初始化集合和對(duì)象。
IList<Student> studentList = new List<Student>() { new Student() { StudentID = 1, StudentName = "John"} , new Student() { StudentID = 2, StudentName = "Steve"} , new Student() { StudentID = 3, StudentName = "Bill"} , new Student() { StudentID = 3, StudentName = "Bill"} , new Student() { StudentID = 4, StudentName = "Ram" } , new Student() { StudentID = 5, StudentName = "Ron" } };
您還可以將null指定為元素:
IList<Student> studentList = new List<Student>() { new Student() { StudentID = 1, StudentName = "John"} , null };
初始化程序語法使代碼更具可讀性,易于將元素添加到集合中。
在多線程中很有用。