2011-12-22 93 views
1

例如:C#空可選參數

void building(int doors, bool multi_story) {...} 
or 
void building(int doors = 1, bool multi_story = false) {...} 

因此:

new building(4, true); 
new building(1, false); 
or 
new building(doors: 4, multi_story: true); 
new building(); 

Thease東西可空運行良好「型?以及。不過,能夠做到這一點很好。

new building(doors: 4, multi_story:); // thanks SLaks for the correction 

意思是「一切都是默認除了 - >有4扇門,是多層的」。刪除一個單詞「真」只是一件小事,但可以模擬這個嗎?

+2

你在問什麼是可空類型? – SLaks 2011-12-22 16:35:19

+2

聽起來我發現,一個布爾參數類型有點糟糕。它的確使用枚舉來代替。 – 2011-12-22 16:45:04

+0

我已經想出了問題的Nullable類型部分的答案,所以我刪除了它,您可以將一個未指定的Nullable 作爲參數,但是不能使用'new'創建該參數永遠不能使用的參數。 – alan2here 2011-12-22 17:17:43

回答

2

否; C#不支持這種語法。

如果您有一個名爲multi_story的本地變量會發生什麼?

+0

你是對的,ty,也許是「(門:4,multi_story :)」我已經在問題中糾正了這個問題,並發表了評論以表明這一點,對不起,它已經過時了你的一些答案。 – alan2here 2011-12-22 17:10:03

+0

你想用新建築物做什麼(門:4,multi_story :);'?它沒有任何意義。也許'新建築(門:4,多層:真);'? – 2011-12-22 17:13:09

+0

這意味着什麼,我想它會是句法糖。對我而言,它在概念上有很大的意義,畢竟「multi_story:false」)會被使用,因爲它是可選的,而不是說「不是」,函數的用戶不會使用該參數,但是要說「是的,有多故事」,必須指明「是的,有多故事,多故事也有價值真」,這對門而言是有用的,但對於那些只是或不是,或者在某種情況下所有關於它的具體說明都是存在的。 – alan2here 2011-12-22 17:25:09

0

你可以這樣寫:

new building(doors: 4); 

甚至:

new building(4); 

如果不指定參數,則默認爲它指定的默認值。所以multi_story將在這裏false

+0

這意味着它不是multi-story,該怎麼指定它?將需要「新建築物(門:4,多層:真);」或「新建築物(多層次:真實)」;如果我想要默認的門數。而不是像「新建築(門:4,多故事:);」 – alan2here 2011-12-22 17:07:36

+0

怎麼c#知道你的意思是'真'?布爾可選參數沒有特殊的規則。那麼「建造(門:)」意味着什麼? -1,0,1或者可以是100.您可以爲可選參數指定值,或者您不指定值。沒有「之間」。 – 2011-12-22 17:17:10

+0

我會想象建築物(門:)會失敗,特別是如果它與「指定但沒有任何=真」完成,因爲數字不能是真/假,也許可選地包括指定的默認值以及未指定的默認值,或者甚至未指定的默認值爲null可能工作正常,除了我喜歡使用null作爲默認值有時。但是,我明白你在說什麼。而且這一切都有些假設,因爲這個概念看起來似乎不存在於C#中。 – alan2here 2011-12-22 17:48:58

0

只要函數的簽名各不相同,您可以使用相同的名稱創建多個函數/方法。

例如

public void building() {...} 
public void building(int doors) {...} 
public void building(bool multiStory) {...} 
public void building(int doors, bool multiStory) {...} 

上面的第一個,會是什麼我在做的是:

public void building() 
{ 
    building(1); // call building passing default doors 
} 
public void building(int doors) 
{ 
    building(doors, true); // call the building function passing the default story flag 
} 
public void building(bool multiStory) 
{ 
    building (1, multiStory); // Call building function passing default doors and ms flag 
} 
public void building(int doors, bool multiStory) 
{ 
    //final building function - deal with doors & story arguments. 
} 

注意,你可以做這樣的事情與類對象的構造函數,使用「this」關鍵字調用下一個構造類似於:

void building() : this(1) {} 
void building(int doors) : this(doors, true) {} 
void building(bool multiStory) :this(1, multiStory) {} 
void building(int doors, bool multiStory){ 
    //do stuff 
} 
+0

這個dosn't根本不使用可選參數,只是簡單的多態性,並且dosn't不會改進我的可選參數示例。我的問題是關於用可選參數表達事物的細節。 – alan2here 2011-12-23 23:51:11