C#:将集合转换为params []

Ily*_*gan 10 c# string-formatting params

这是我的代码的简化:

void Foo(params object[] args)
{
    Bar(string.Format("Some {0} text {1} here {2}", /* I want to send args */);
}
Run Code Online (Sandbox Code Playgroud)

string.Format要求发送的参数为params.有没有什么方法可以将args集合转换为string.Format方法的参数?

Mår*_*röm 13

params关键字只有语法糖,让您打电话与任意数量的参数这样的方法.但是,这些参数始终作为数组传递给方法.

这意味着Foo(123, "hello", DateTime.Now)相当于Foo(new object[] { 123, "hello", DateTime.Now }).

因此,你可以Foo直接将参数传递给string.Format这样:

void Foo(params object[] args)
{
  Bar(string.Format("Some {0} text {1} here {2}", args));
}
Run Code Online (Sandbox Code Playgroud)

但是,在这种特殊情况下,您需要三个参数(因为您的格式中有{0},{1}和{2}.因此,您应该将代码更改为:

void Foo(object arg0, object arg1, object arg2)
{
  Bar(string.Format("Some {0} text {1} here {2}", arg0, arg1, arg2));
}
Run Code Online (Sandbox Code Playgroud)

......或者像马塞洛建议的那样做.