如何创建同时包含可选参数和参数的方法?
static void Main(string[] args) { TestOptional("A",C: "D", "E");//this will not build TestOptional("A",C: "D"); //this does work , but i can only set 1 param Console.ReadLine(); } public static void TestOptional(string A, int B = 0, params string[] C) { Console.WriteLine(A); Console.WriteLine(B); Console.WriteLine(C.Count()); }
现在唯一的选择是重载TestOptional(就像在C#4之前所做的那样)。不是首选,但是它会在使用时清理代码。
public static void TestOptional(string A, params string[] C) { TestOptional(A, 0, C); } public static void TestOptional(string A, int B, params string[] C) { Console.WriteLine(A); Console.WriteLine(B); Console.WriteLine(C.Count()); }