【C#高效编程50例】条目1:使用属性而不是可访问的数据成员

书名:《C#高效编程 改进C#代码的50个行之有效的方法》

条目1 使用属性而不是可访问的数据成员

1 属性格式

        private string _scustomerName = string.Empty;
        public string CustomerName
        {
            get
            { return _scustomerName; }
            set
            { _scustomerName = value; }
        }

2 可以为Set get 指定不同的访问权限, 如 为get指定私有的

        private string _scustomerName = string.Empty;
        public string CustomerName
        {
            private get
            { return _scustomerName; }
            set
            { _scustomerName = value; }
        }

3 属性比数据成员易于维护、修改,比如用户名不能为空,则在属性里直接加现在就可以

private string _scustomerName = string.Empty;
        public string CustomerName
        {
            private get
            { return _scustomerName; }
            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    throw new Exception("Customer can not be blank.", "Name");
                }
                _scustomerName = value;
            }
        }

4 支持多线程,可以在属性里是实现同步

private object obj = new object();
        private string _scustomerName = string.Empty;
        public string CustomerName
        {
            private get
            {
                lock (obj)
                    return _scustomerName;
            }
            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    throw new Exception("Customer can not be blank.", "Name");
                }
                lock (obj)
                    _scustomerName = value;
            }
        }

5 像方法一样,可以为Virtual的

public virtual string CustomerName
        {
            get;
            set;
        }
6 也可以声明为抽象的 abstract

public interface INameValuePair<T>
        {
            string Name
            {
                get;
            }

            T Value
            {
                get;
                set;
            }
        }

7 get 和 set 作为两个方法,独立的编译

8 支持参数的属性:索引器

public int this[int index]
        {
            get
            { return theValue[index]; }
            set
            {
                theValue[index] = value;
            }
        }
 

9 属性和数据成员在代码层面上是兼容的,但是在二进制层面上不一样。

 属性和数据成员的访问,也会生成不同的MSIL,微软中间语言指定。

访问属性和访问数据成员的性能差距很小。

属性的访问器里不应该进行长时间的计算,因为用户期待访问属性就像访问数据成员一样。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值