假设我想要调用此方法,并且它来自第三方库,因此我无法更改其签名:
void PrintNames(params string[] names)
我正在写这个需要调用的方法PrintNames:
void MyPrintNames(string[] myNames) {
// How do I call PrintNames with all the strings in myNames as the parameter?
}
Run Code Online (Sandbox Code Playgroud)
我会尝试
PrintNames(myNames);
Run Code Online (Sandbox Code Playgroud)
你会知道你是否看过MSDN上的规范:http://msdn.microsoft.com/en-us/library/w5zay9db.aspx
他们非常清楚地证明了这一点 - 请注意示例代码中的注释:
// An array argument can be passed, as long as the array
// type matches the parameter type of the method being called.
Run Code Online (Sandbox Code Playgroud)
当然.编译器会将多个参数转换为数组,或者让您直接传入数组.
public class Test
{
public static void Main()
{
var b = new string[] {"One", "Two", "Three"};
Console.WriteLine(Foo(b)); // Call Foo with an array
Console.WriteLine(Foo("Four", "Five")); // Call Foo with parameters
}
public static int Foo(params string[] test)
{
return test.Length;
}
}
Run Code Online (Sandbox Code Playgroud)