第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

初始化C#自動(dòng)屬性

初始化C#自動(dòng)屬性

C#
SMILET 2019-10-16 15:00:18
我習(xí)慣于編寫這樣的類:public class foo {  private string mBar = "bar";  public string Bar {    get { return mBar; }    set { mBar = value; }  }  //... other methods, no constructor ...}將Bar轉(zhuǎn)換為自動(dòng)屬性似乎方便且簡(jiǎn)潔,但是如何在不添加構(gòu)造函數(shù)并將初始化放在其中的情況下保留初始化?public class foo2theRevengeOfFoo {  //private string mBar = "bar";  public string Bar { get; set; }  //... other methods, no constructor ...  //behavior has changed.}您可能會(huì)看到,添加構(gòu)造函數(shù)并不符合我應(yīng)該從自動(dòng)屬性中節(jié)省的工作量。這樣的事情對(duì)我來說更有意義:public string Bar { get; set; } = "bar";
查看完整描述

3 回答

?
三國紛爭(zhēng)

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)值。


查看完整回答
反對(duì) 回復(fù) 2019-10-16
?
蝴蝶不菲

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ā)生的事情。


查看完整回答
反對(duì) 回復(fù) 2019-10-16
  • 3 回答
  • 0 關(guān)注
  • 743 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)