越来越人性化的.Net C#,VB.Net语言特性:自动属性,对象初始化器和集合初始化器 [转]
Posted on 2007-08-27 12:58 基点项目师 阅读(778) 评论(1) 编辑 收藏 举报--------------------------------------------------------------------------------
引用或转载时请保留以下信息:
大可山 [MSN:a3news(AT)hotmail.com]
http://www.zpxp.com http://www.brawdraw.com
萝卜鼠在线图形图像处理
--------------------------------------------------------------------------------
1. 自动属性(Automatic Properties)
相信C#开发者都曾遇到类似如下繁琐的get/set:
(重复性的机械劳动啊!我曾经为此而心烦不已,后来干脆在VS中安装一个叫VSProperty的插件)
public class Person
{
private string _trueName;
private string _nickName;
private int _age;
public string TrueName
{
get {
return _trueName;
}
set {
_trueName= value;
}
}
public string NickName
{
get {
return _nickName;
}
set {
_nickName= value;
}
}
public int Age
{
get {
return _age;
}
set {
_age = value;
}
}
}
庆幸的是,在VS2008中有了改观,你可以这样了:
public class Person
{
public string TrueName { get; set; }
public string NickName { get; set; }
public int Age { get; set; }
}
2. 对象初始化器(Object Initializers):
之前初始化方式:
Person person = new Person();
person.TrueName = "Johson";
person.NickName = "大可山";
person.Age = 30;
现在你可以:
Person person = new Person { TrueName="Johnson", NickName = "大可山", Age=30 }; //一行搞定,真是方便!
要加上通讯地址怎么办?
可以改成:
Person person = new Person
{
TrueName = "Johnson",
NickName = "大可山"
Age = 30,
Address = new Address {
Street = "福田区深南大道6008号深圳报业集团",
City = "深圳市",
Province = "广东省",
Zip = 518009
}
};
注意看Address也是新加的,直接new!
3.集合初始化器(Collection Initializers)
可以使用这样:
List<Person> people = new List<Person>();
people.Add( new Person { TrueName = "Johnson", NickName = "大可山", Age = 30 } );
people.Add( new Person { TrueName = "Bill", NickName = "比尔大哥", Age = 40 } );
people.Add( new Person { TrueName = "Jim", NickName = "小靓哥", Age = 20 } );
甚至可以这样:
List<Person> people = new List<Person> {
new Person { TrueName = "Johnson", NickName = "大可山", Age = 30 },
new Person { TrueName = "Bill", NickName = "比尔大哥", Age = 40 },
new Person { TrueName = "Jim", NickName = "小靓哥", Age = 20 }
};
(又少了几个Add)
一句话,越来越人性化了!