由於默認參數值必須是編譯時表達式,因此參考類型的唯一可接受的默認參數值爲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>())
...
}
雖然顯然是一個簡單的,如果後衛能夠更有效。實際上取決於如果你希望把它當作一個空的枚舉或爲空列表或只是旁路邏輯...
BTW,參數類型應該是儘可能地寬。最好是使用IList或者最好是IEnumerable –
SLaks
我從來沒有在accept機制的任何地方找到清晰的指令。看看FAQ,我沒有看到它的信息......? –
@StephenGross,只需勾選最有可能幫助未來訪問者的問題旁邊的綠色框即可。 :) – bzlm