3 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超7個(gè)贊
您可以通過類的構(gòu)造函數(shù)來實(shí)現(xiàn):
public class foo {
public foo(){
Bar = "bar";
}
public string Bar {get;set;}
}
如果您有另一個(gè)構(gòu)造函數(shù)(即使用參數(shù)的構(gòu)造函數(shù))或一堆構(gòu)造函數(shù),則可以始終使用此構(gòu)造函數(shù)(稱為構(gòu)造函數(shù)鏈接):
public class foo {
private foo(){
Bar = "bar";
Baz = "baz";
}
public foo(int something) : this(){
//do specialized initialization here
Baz = string.Format("{0}Baz", something);
}
public string Bar {get; set;}
public string Baz {get; set;}
}
如果您始終將調(diào)用鏈接到默認(rèn)構(gòu)造函數(shù),則可以在那里設(shè)置所有默認(rèn)屬性初始化。鏈接時(shí),鏈接的構(gòu)造函數(shù)將在調(diào)用構(gòu)造函數(shù)之前被調(diào)用,以便您更專業(yè)的構(gòu)造函數(shù)將能夠在適用時(shí)設(shè)置不同的默認(rèn)值。

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
在默認(rèn)構(gòu)造函數(shù)中(當(dāng)然也可以在任何非默認(rèn)構(gòu)造函數(shù)中):
public foo() {
Bar = "bar";
}
我相信這與原始代碼的性能一樣好,因?yàn)闊o論如何這都是幕后發(fā)生的事情。
- 3 回答
- 0 關(guān)注
- 743 瀏覽
添加回答
舉報(bào)