编辑这个页面须要登录或更高权限!
C#3.0(.NET 3.5)引入了对象初始化器语法,这是一种初始化类或集合对象的新方法。对象初始化程序允许您在创建对象时将值分配给字段或属性,而无需调用构造函数。
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" }; } }
在上面的示例中,没有任何构造函数的情况下定义了 Student 类。在 Main() 方法中,我们创建了Student对象,并同时为大括号中的所有或某些属性分配了值。这称为对象初始化器语法。
编译器将上述初始化程序编译为如下所示的内容。
Student __student = new Student(); __student.StudentID = 1; __student.StudentName = "Bill"; __student.Age = 20; __student.StandardID = 10; __student.Address = "Test"; Student std = __student;
可以使用集合初始化器语法以与类对象相同的方式初始化集合。
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 };
您还可以同时初始化集合和对象。
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 };
初始化程序语法使代码更具可读性,易于将元素添加到集合中。
在多线程中很有用。