越来越人性化的.Net C#,VB.Net语言特性:自动属性,对象初始化器和集合初始化器

116 篇文章 9 订阅

--------------------------------------------------------------------------------
引用或转载时请保留以下信息:
大可山 [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)

一句话,越来越人性化了!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值