private int dd;
public int dd
{
get{ return xx*3;}
set{ xx = value/3;}
}
沒有set的屬性是一種只讀屬性,沒有get的訪問器是一種只寫屬性。
(1) get訪問器用來返回字段或者計算 并返回字段,它必須以return或者throw終結。
private string name;
public string Name
{
get
{
return name != null ? name : "NA";
}
}
(2) set訪問器類似返回類型為void的函數,使用value的隱式參數
private string name; // the name field
public string Name // the Name property
{
get
{
return name;
}
set
{
name = value;
}
}
(3) 訪問器的限制
屬性訪問標記可以為public,private,protected,internal,protected internal,因為訪問器的訪問限制必須比屬性的訪問限制更加嚴格,所以
private int xx;
public int sxx
{
public get { return xx; }//error
set { xx = value; }
}
不能對接口或者顯式的接口使用訪問修飾符,因為接口里里面所有的默認是public的;
同時具有get,set訪問器時,才允許使用訪問修飾符,并且只能有一個使用;
如果屬性有override修飾的時候,訪問器修飾符必須與被重寫的匹配。
訪問器的可訪問級別必須比屬性的可訪問級別更加嚴格理解:
首先第四條最容易想到,也是很合理的,畢竟是外圍的決定內部的。
其次,既然第四條可以理解,那么如果只有一個訪問器的時候,訪問器訪問級別等同屬性,如果這個時候再去指 定更加嚴格的訪問級別,那么為何不當初在屬性上指定呢?
這條理解了,那么為什么必須同時具有get,set才能添加訪問修飾符就更加明確了。
推理:
接口中屬性是public的,那么如果接口中只有一個get或者set的時候,我們可以在繼承中指明另一個訪問器的屬 性。但是如果接口中同時具有get,set,那么按照派生和繼承的匹配性,這時候就不能這樣再指定訪問器的訪問限制了。
public interface ISomeInterface
{
int TestProperty
{
// No access modifier allowed here
// because this is an interface.
get;
}
}
public class TestClass : ISomeInterface
{
public int TestProperty
{
// Cannot use access modifier here because
// this is an interface implementation.
get { return 10; }
// Interface property does not have set accessor,
// so access modifier is allowed.
protected set { }
}
}
(4)可以用static 修飾屬性,以便隨時訪問
private static int counter;
public static int Counter
{
get { return counter; }
}
(5)屬性隱藏
public class Employee
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
public class Manager : Employee
{
private string name;
// Notice the use of the new modifier:
public new string Name // use new to hide property in base class
{
get { return name; }
set { name = value + ", Manager"; }
}
}
(6)virtual來修飾屬性,派生類使用override來重寫屬性
public class Parent
{
public virtual int TestProperty
{
protected set { }
get { return 0; }
}
}
public class Kid : Parent
{
public override int TestProperty
{
protected set { }
get { return 0; }
}
}
(7) abstract 修飾屬性,派生類來實現屬性
abstract class Shape
{
public abstract double Area
{
get;
set;
}
}
class Square : Shape
{
public double side;
public override double Area
{
get
{
return side * side;
}
set
{
side = System.Math.Sqrt(value);
}
}
}
(8)sealed 修飾屬性,派生類不能修改屬性
(9)接口屬性
接口屬性不具有函數體
public interface Inters
{
string Name
{
get;
set;
}
}
(10) 自動屬性
當屬性訪問器中不需要其他訪問邏輯時候,就可以使用自動屬性,使代碼更加簡潔
public double TotalPurchases { get; set; }
public string Name { get; set; }
public int CustomerID { get; set; }