繁体   English   中英

在C#中,是否可以将数组传递给采用可变长度参数的方法?

[英]In C#, is there a way to pass an array to a method that takes in a variable length parameters?

假设我有一个要调用的方法,它来自第三方库,因此我无法更改其签名:

void PrintNames(params string[] names)

我正在写这种方法,需要调用PrintNames

void MyPrintNames(string[] myNames) {
  // How do I call PrintNames with all the strings in myNames as the parameter?
}

我会尝试

PrintNames(myNames);

您将知道是否可以查看MSDN上的规范: http : //msdn.microsoft.com/zh-cn/library/w5zay9db.aspx

他们非常清楚地展示了它-请注意示例代码中的注释:

// An array argument can be passed, as long as the array 
// type matches the parameter type of the method being called. 

当然。 编译器会将多个参数转换成一个数组,或者只是让您直接传递一个数组。

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;
   }
}

小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM