2011-10-12 742 views
2

我有一個C#方法,需要一堆參數,所有參數都有默認值。其中一個參數是List。我無法弄清楚如何指定列表應該默認爲空。下面是它的樣子:如何在c#函數中爲List <>參數指定默認值?

public static void execute(
     String condition = "Unnamed condition", 
     List<String> messages, 
     Object actual = null, 
     Object expected = null) 

我不能完全弄清楚如何指定消息應該默認爲空。當我輸入時:

... 
List<String> messages = new List<String>() 
... 

它抱怨說「消息的默認參數值必須是編譯時常量」。

任何想法?

+0

BTW,參數類型應該是儘可能地寬。最好是使用IList 或者最好是IEnumerable SLaks

+0

我從來沒有在accept機制的任何地方找到清晰的指令。看看FAQ,我沒有看到它的信息......? –

+0

@StephenGross,只需勾選最有可能幫助未來訪問者的問題旁邊的綠色框即可。 :) – bzlm

回答

9

由於默認參數值必須是編譯時表達式,因此參考類型的唯一可接受的默認參數值爲null

可以解決這個問題有過載,雖然:

public static void execute(String condition = "Unnamed condition") 
{ 
    execute(condition, new List<String>(), null, null); 
} 

或建造列表,如果該參數是null。如果您需要列表並且想要將所有null作爲空列表處理,則它們也可以在明確調用null時處理。

public static void execute(String condition = "Unnamed condition", 
     List<String> messages = null, Object actual = null, 
     Object expected = null) 
{ 
    // if you really want this to be empty if null, can check and assign. 
    if (messages == null) 
    { 
     messages = new List<String>(); 
    } 

    // your other logic 
} 

或者,如果消息是隻在一個地方使用時,您可以使用空coallescing操作來代替空枚舉:

public static void execute(String condition = "Unnamed condition", 
     List<String> messages = null, Object actual = null, 
     Object expected = null) 
{ 
    // assuming you are using messages once for iteration or something... 
    foreach(var msg in messages ?? Enumerable.Empty<String>()) 
    ... 
} 

雖然顯然是一個簡單的,如果後衛能夠更有效。實際上取決於如果你希望把它當作一個空的枚舉或爲空列表或只是旁路邏輯...

2

messages默認null的歡迎,並在函數體內檢查是否其null和appropiately處理它(或用new List()替換它)。

2

編譯器接受的唯一東西是null。如果方便的話給你,你的方法將需要測試這種情況下,並替換空單:

if(messages==null) { 
    messages=new List<String>(); 
} 
1

編譯器告訴你爲什麼:默認參數必須是編譯時間常數。顯然,動態分配和構建的列表不適合該描述。最簡單的解決方法是使默認值null,然後在您的方法中,如果參數是null,創建實際的默認列表。

3

由於錯誤消息明確指出,您不能將引用類型的任意實例作爲默認值。
您可以使用的全部是文字,const s或null

相反,你可以將默認設置爲null,然後寫

messages = messages ?? new List<string>(); 
相關問題