2009年2月10日 星期二

C# 函式 ref out getter setter

C#函式的參數傳遞有分三種 call By Value,call By Refeance,Output parameter
第一種就是最原始的參數傳遞,也就是函式運作不改變
call By Value範例
int swap(a,b){....}
int x,y;
x=1;
y=2;
......
swap(x,y);


上面範例 a,b,x,y都是使用不同記憶體 x,y的值不會被改變

第二種是參數跟變數共用記憶體 變數會被函式影響
call By Refeance範例
int swap(ref a,ref b){....}
int x,y;
x=1;
y=2;
......
swap(ref x,ref y);


上面範例 a跟x是同一份記憶體 b跟y是同一份記憶體
x,y會被函式swap改變

第三種就跟call By Refeance很像
變數跟參數共用記憶體,但是變數不需要指派初始值
變數的值由函式賦予
int setValue(out a,out b){....}
int x,y;
......
setValue(out x,out y);




再來介紹setter跟getter的語法

class AT {


public AT()
{
_x = 100;
_y = 200;
}
private int _x;
private int _y;
/*getter setter屬性封裝測試*/
public int Attr {

get {
return _x;
}
set
{
if (value < 0)
{
_x = 0;
}
else
{
_x = value;
}
}
}
/*唯獨屬性測試*/
public int ReadOnly
{
get {
return _y;
}
/*要建立唯獨屬性 就是只設立get*/
/*要建立唯寫屬性 就是只設立set*/
/*如果唯獨嘗試設值會編譯不過*/

}

}

沒有留言: