English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C#3.0 (.NET 3.5) ha introdottoSintassi dell'inizializzatore dell'oggettoQuesta è una nuova metodo di inizializzazione della classe o dell'oggetto della raccolta. L'inizializzatore dell'oggetto consente di assegnare valori ai campi o alle proprietà durante la creazione dell'oggetto senza chiamare il costruttore.
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" }; } }
Nell'esempio precedente, la classe Student è stata definita senza alcun costruttore. Nel metodo Main(), abbiamo creato l'oggetto Student e contemporaneamente abbiamo assegnato valori a tutti o alcuni degli attributi tra le parentesi graffe. Questo si chiama sintassi dell'inizializzatore dell'oggetto.
Il compilatore compila il programma di inizializzazione come segue.
Student __student = new Student(); __student.StudentID = 1; __student.StudentName = "Bill"; __student.Age = 20; __student.StandardID = 10; __student.Address = "Test"; Student std = __student;
È possibile utilizzare la sintassi dell'inizializzatore dell'insieme per inizializzare un insieme nello stesso modo in cui si inizializza un oggetto di classe.
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 };
È possibile inizializzare contemporaneamente l'insieme e l'oggetto.
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 };
初始化程序语法使代码更具可读性,易于将元素添加到集合中。
在多线程中很有用。