原因:
1. 所有的bind方法綁定屬性。
data bind的機制是使用反射的方法,通過屬性名稱調用相應的方法。
2.使用屬性讓程序更有彈性。
如戶要求名字不能爲空,只要如下修改程序即可
public class Customer{
private string _name;
public string Name
{
get { return _value;}
set
{
//判定是否爲空,如果是空拋出錯誤
if (string.IsNullorEmpty(value))
throw new ArgumentException("名字不能不填寫",“name");
name = value;
}
}
}
3. 可以很容易的增加多線程支持
public class Customer{
private object syncHandle = new object()
private string _name;
public string Name
{
get
{
lock(syncHandle ){return _value;}
}
set
{
//判定是否爲空,如果是空拋出錯誤
if (string.IsNullorEmpty(value))
throw new ArgumentException("名字不能不填寫",“name");
lock(syncHandle ){name = value;}
}
}
}
4. 屬性可以使用虛函數
public class Customer{
public virtual strring Name
{
set;
get;
}
}
屬性定義也可以採用以上的簡略方式。編譯器會自動加上私有的局部變量及屬性的方法體定義。
5.屬性可以在接口中進行定義
public interface INameValuePaire<T>
{
string Name
{
get;
}
T value
{
get;
set;
}
}
所有在普通方法上適應的結構,在屬性中都適應。比如你可以把get方法的訪問範圍定義爲public,把set方法的訪問範圍定義爲protected.
public class Customer{
public virtual strring Name
{
protected set;
get;
}
}
6.屬性也可以定義成數組,進行訪問
- 一維數組的屬性定義
public int this[int index]
{
get {return theValues[index];}
set{ theValues[index] = value;}
}
//屬性的使用
int val = someObject[index]
- directionary或map數據類型的屬性定義
- 多維數組的定義方法與一維數組類似。如:
{
get { return ComputeValue(x, y); }
}
{
get { return ComputeValue(x, Name); }
}
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get
{
return arr[i];
}
set
{
arr[i] = value;
}
}
}
// This class shows how client code uses the indexer
class Program
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
stringCollection[0] = "Hello, World";
System.Console.WriteLine(stringCollection[0]);
}
}