English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C#3.0 (.NET 3.5introduziuSintaxe do inicializador de objetosIsso é uma nova maneira de inicializar classes ou objetos de conjunto. O programa de inicialização de objetos permite que você atribua valores aos campos ou propriedades ao criar o objeto, sem chamar o construtor.
public class Student { public int IDAluno { get; set; } public string NomeAluno { get; set; } public int Idade { get; set; } public string Endereco { get; set; } } class Program { static void Main(string[] args) { Student std = new Student() { IDAluno = 1, NomeAluno = "Bill", Idade = 20, Endereco = "Nova Iorque" }; } }
No exemplo acima, a classe Student foi definida sem nenhum construtor. No método Main(), criamos um objeto Student e atribuímos valores a todos ou a alguns dos atributos dentro dos parênteses de chaves. Isso é chamado de sintaxe do inicializador de objeto.
O compilador compila o inicializador acima para o seguinte conteúdo.
Student __student = new Student(); __student.IDAluno = 1; __student.NomeAluno = "Bill"; __student.Idade = 20; __student.IDPadrão = 10; __student.Endereco = "Test"; Student std = __student;
Você pode usar a sintaxe do inicializador de conjunto para inicializar conjuntos da mesma forma que objetos de classe.
var student1 = new Student() { IDAluno = 1, NomeAluno = "John"}; var student2 = new Student() { IDAluno = 2, NomeAluno = "Steve"}; var student3 = new Student() { IDAluno = 3, NomeAluno = "Bill"}; var student4 = new Student() { IDAluno = 3, NomeAluno = "Bill"}; var student5 = new Student() { IDAluno = 5, NomeAluno = "Ron"}; IList<Student> studentList = new List<Student>() { student1, student2, student3, student4, student5 };
Você também pode inicializar conjuntos e objetos simultaneamente.
IList<Student> studentList = new List<Student>() { new Student() { StudentID = 1, StudentName = "John"}, , new Student() { StudentID = 2, NomeAluno = "Steve"} new Student() { StudentID = 3, NomeAluno = "Bill"} new Student() { StudentID = 3, NomeAluno = "Bill"} new Student() { StudentID = 4, StudentName = "Ram" } , new Student() { StudentID = 5, StudentName = "Ron" }, };
Você também pode especificar null como elemento:
IList<Student> studentList = new List<Student>() { new Student() { StudentID = 1, StudentName = "John"}, , null };
A sintaxe do inicializador torna o código mais legível e facilita a adição de elementos à coleção.
Muito útil em multithreading.