Vas*_*sea 104
只需使用null合并运算符和空List的实例
public void Process(string param1, List<string> param2 = null) {
param2 = param2 ?? new List<String>();
}
Run Code Online (Sandbox Code Playgroud)
这样做的问题是,如果"param2"为null并且您分配了一个新引用,那么它将无法在调用上下文中访问.
Him*_*ere 17
您也可以使用default哪个IS编译时常量(null在a的情况下List<T>):
void DoSomething(List<string> lst = default(List<string>))
{
if (lst == default(List<string>)) lst = new List<string>();
}
Run Code Online (Sandbox Code Playgroud)
是不可能的。您应该改用方法重载。
public static void MyMethod(int x, List<string> y) { }
public static void MyMethod(int x)
{
MyMethod(x, Enumerable<string>.Empty());
}
Run Code Online (Sandbox Code Playgroud)