書名:《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,微軟中間語言指定。
訪問屬性和訪問數據成員的性能差距很小。
屬性的訪問器裏不應該進行長時間的計算,因爲用戶期待訪問屬性就像訪問數據成員一樣。