2.對象初始化器,原來的對象初始化都要進行先創建構造方法,然後才能進 行成員的相關操作,C#3.0 提供了對象成員的直接初始化的能力,和初始化一個 集合或者是數組一樣來初始化對象。
相面來看,通過對象初始化器對上 面的的Employee類進行進行調用:
Employee employee = new Employee { Id = 1, Name = "藍之風", Age = 24, BirthDate =
"1984-10-21", Sex = "男 " };
Console.WriteLine("編號;{0}", employee.Id);
Console.WriteLine("姓名:{0}", employee.Name);
Console.WriteLine("年齡:{0}", employee.Age);
Console.WriteLine("生日:{0}", employee.BirthDate);
Console.WriteLine("性別:{0}", employee.Sex);
Console.WriteLine("請按任意鍵繼 續...");
Console.ReadLine();
這句Employee employee = new Employee { Id = 1, Name = "藍之風", Age = 24,
BirthDate = "1984-10-21", Sex = "男 " };
就是對象的初始化,看到代碼很簡潔,輸出的結果如 下:
在C#3.0之前的做法是:
Employee employee = new Employee();
employee.Id = 1;
employee.Name = "藍 之風";
employee.Age = 24;
employee.BirthDate = "1984-10-21";
employee.Sex = "男";
Console.WriteLine("編號;{0}", employee.Id);
Console.WriteLine("姓名:{0}", employee.Name);
Console.WriteLine("年齡:{0}", employee.Age);
Console.WriteLine("生日:{0}", employee.BirthDate);
Console.WriteLine("性別:{0}", employee.Sex);
Console.WriteLine("請按任意鍵繼續...");
Console.ReadLine();