.Net 3.5新特性(1)Automatic Properties, Object Initializers, and Collection Initializers

1) Automatic Properties自动属性 如果你之前使用的是.NET 2.0或者你不熟悉.NET 3.5的新特性,你可能经常写出以下的代码:

定义属性
public class Person
{
private string firstName;
private string lastName;
private int age;

public string FirstName
{
get { return firstName; }
set { firstName = value; }
}

public string LastName
{
get { return lastName; }
set { lastName = value; }
}

public int Age
{
get { return age; }
set { age = value; }
}
}

 事实上,在上面的代码中我们并没有为属性中的get/set添加任何的逻辑,为什么不适用数据成员(field)呢?两个主要原因是:

1). 无法轻松地对数据成员进行数据绑定;

2). 当你把公开的数据成员转成属性的时候,必须编译类的代码,同时也必须编译访问该类实例的代码,否则,无法使原来的代码正常使用

.NET3.5引进新的特性” Automatic Properties”,即自动属性,避免声明private的数据成员和get/set逻辑。编译器会自动创建私有的数据成员并完成get/set操作 使用.net3.5修改以上代码如下:

自动属性
1 public class Person
2 {
3 public string FirstName { get; set; }
4 public string LastName { get; set; }
5 public int Age { get; set; }
6 }

2) Object Initializers对象初始化器 当使用一个类,并对类中的属性进行赋值是,我们经常这样写:

对象初始化
1 Person person = new Person();
2 person.FirstName = "Xiao Tian";
3 person.LastName = "Chen"; person.Age = 26;

是否想过使用更加简洁的写法呢?尝试下对象初始化器吧,修改代码如下:

对象初始化(new)
1 Person person = new Person(){FirstName="Xiao Tian",LastName="Chen",Age = 26};

够爽吧,除了这种简单的属性初始化外,对象初始化器还允许我们进行嵌套,参考如下代码:

嵌套对象初始化
1 Person person = new Person { FirstName = "Scott",
2 LastName = "Guthrie",
3 Age = 32,
4 Address = new Address { Street = "One Microsoft Way", City = "Redmond", State = "WA", Zip = 98052 }
5 };

3) Collection Initializers集合初始化器 对象初始化器很强大,同时,他也简化了将对象添加到集合的操作。

例如,我要添加3个Person到泛型集合中,可以这样写:

集合初始化
1 List people = new List();
2
3 people.Add( new Person { FirstName = "Scott", LastName = "Guthrie", Age = 32 } );
4
5 people.Add( new Person { FirstName = "Bill", LastName = "Gates", Age = 50 } );
6
7 people.Add( new Person { FirstName = "Susanne", LastName = "Guthrie", Age = 32 } );

通过使用对象初始化器,我们节省了很多代码,但是,集合初始化器允许我们更进一步简化:

集合初始化(new)
1 List people = new List { new Person { FirstName = "Scott", LastName = "Guthrie", Age = 32 },
2 new Person { FirstName = "Bill", LastName = "Gates", Age = 50 },
3 new Person { FirstName = "Susanne", LastName = "Guthrie", Age = 32 }
4 }

原文参考:http://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspx

原文地址:https://www.cnblogs.com/tian2010/p/2097830.html