struct Screen Position
{
...
public int X
{
get {...}
set {...}
}
...
}
2、為結(jié)構(gòu)或者類聲明一個(gè)只讀屬性
struct Screen Position
{
...
public int X
{
get {...}
}
...
}
3、為結(jié)構(gòu)或者類聲明一個(gè)只寫(xiě)屬性
struct Screen Position
{
...
public int X
{
set {...}
}
...
}
4、在接口中聲明一個(gè)屬性
interface IScreenPosition
{
int X{get;set;}
int Y {get;set;}
}
5、在結(jié)構(gòu)或者類中實(shí)現(xiàn)一個(gè)接口屬性
struct ScreenPosition:IScreenPosition
{
public int X{...}
public int Y {...}
}
6、創(chuàng)建一個(gè)自動(dòng)屬性
class Polygon
{
public int NumSides { get; set; }
public double SideLength { get; set; }
public Polygon()
{
this.NumSides = 4;
this.SideLength = 10.0;
}
}
Polygon square = new Polygon();
Polygon triangle = new Polygon { NumSides = 3 };
Polygon pentagon = new Polygon { SideLength = 15.5, NumSides = 5 };
注:
只有在一個(gè)結(jié)構(gòu)或類初始化好之后,才能通過(guò)這個(gè)結(jié)構(gòu)或類的屬性來(lái)進(jìn)行賦值。
ScreenPosition location;
location.X=40;//編譯時(shí)錯(cuò)誤,location尚未使用new來(lái)初始化
不可將屬性作為一個(gè)ref或者out參數(shù)值傳給一個(gè)方法;但可以將一個(gè)可寫(xiě)的字段作為ref或out參數(shù)值來(lái)傳遞。這是由于屬性并不真正指向一個(gè)內(nèi)存位置,相反,它指向的是一個(gè)訪問(wèn)方法。
在一個(gè)屬性中,最多只能包含一個(gè)get accessor和一個(gè)set accessor。屬性不能包含其它方法、字段或?qū)傩浴?/strong>
get accessor和set accessor不能獲取任何參數(shù)。要賦的值會(huì)通過(guò)內(nèi)建的、隱藏的value變量,自動(dòng)傳給set accessor。
不能聲明const屬性。如
const int X{get{...}set{...}}//編譯時(shí)錯(cuò)誤