C#3.0中自动属性和对象初始化器
2009-04-24 08:25:48 来源:WEB开发网上图中的IL代码中我们看到了
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();
更多精彩
赞助商链接