W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
任何可訪問的字段或?qū)ο蟮膶傩钥梢栽跇?gòu)造之后通過對(duì)象初始化器直接設(shè)置。
例如,考慮下面的類:
public class Person {
public string Name;
public bool IsWorking;
public bool HasChild;
//from ww w . j av a 2 s .c o m
public Person () {}
public Person (string n) {
Name = n;
}
}
使用對(duì)象初始化器,您可以如下所示實(shí)例化Person對(duì)象:
// Note parameterless constructors can omit empty parentheses
Person b1 = new Person { Name="Jack", IsWorking=true, HasChild=false };
Person b2 = new Person ("Jack") { IsWorking=true, HasChild=false };
我們可以使Person的構(gòu)造函數(shù)接受可選參數(shù):
public Person (string name, bool IsWorking = false, bool HasChild = false) {
Name = name;
IsWorking = IsWorking;
HasChild = HasChild;
}
這將允許我們構(gòu)造一個(gè)Person如下:
Person b1 = new Person (name: "Jack", IsWorking: true);
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: