English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C#3.0 (.NET 3.5)introdujoSintaxis del inicializador de objetos,Esta es una nueva forma de inicializar clases o objetos de conjuntos. El programa de inicialización de objetos permite asignar valores a campos o propiedades al crear el objeto, sin necesidad de llamar al constructor.
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" } };
También puede especificar null como elemento:
IList<Student> studentList = new List<Student>() { new Student() { StudentID = 1, StudentName = "John"} , null };
La sintaxis de inicializador hace que el código sea más legible y fácil de agregar elementos a la colección.
Muy útil en multihilo.