很多時候我們不可以把一些字段暴露出來允許別人調用和修改,為了隱藏這些字段又便於加限制的使用,在面向對象編程中一般采用寫get set函數的辦法,比如:
//字段_age, "_"表示private
private int _age;
//獲取字段值的方法,需要返回這個int類型字段
public int GetAge()
{
return this._age;
}
//設置字段值的方法,不需要返回值,定義一個int類型的value
public void SetAge(int value)
{
if (value >= 0 && value <= 120)//可以加條件來限制字段的范圍
{
this._age = value;
}
else
{
throw new Exception ("Age value has error.");
}
}
學生的年齡限制在0-120,則可以避免20歲輸入成200歲這種錯誤。
C#語言單獨引入了屬性這種概念,用來對字段加以限制,屬性是一種語法糖。
//字段_age, "_"表示private
private int _age;
public int Age
{
//獲取字段值的方法
get
{
return this._age;
}
//設置字段值的方法,不需要返回值
set
{
if (value >= 0 && value <= 120)//規定好value是上下文關鍵字(藍色)
{
this._age = value;
}
else
{
throw new Exception("Age value has error.");
}
}
}
只讀方法:(不允許往里寫,只允許讀取的方法。另外只寫方法是沒有意義的,因此不舉例只寫方法)
//字段_age, "_"表示private
private int _age;
public int Age
{
//獲取字段值的方法
get
{
return this._age;
}
}
屬性快捷鍵
propfull 然后按兩下tab會出現
private int myVar;
public int MyProperty
{
get { return myVar; }
set { myVar = value; }
}
最簡單:(這種屬性沒有任何保護,與一個公有的字段完全一樣,很容易被改變值,帶有這種屬性的類一般是傳輸數據用的)
public int Age{get;set;}
索引器:Indexer
基本語法:
修飾符 類型名 this [參數列表] //this表示他是個索引器
{
get{
}
set{
}
}
舉個例子:
public string s;
//可容納100個整數的整數集
private string[] arr = new string[10];
//聲明索引器
public string this[int index]//這里定義一個index
{
get
{ //檢查索引范圍
if (index < 0 || index >= 10)
{
return null;
}
else
{
return arr[index];
}
}
set
{
if (!(index < 0 || index >= 100))
{
arr[index] = value;
}
}
}