【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,微软中间语言指定。

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

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章