将数组解压缩为方法参数

4 c# arrays syntax params-keyword variadic-functions

如您所知,C#通过params关键字支持可变方法:

int Add(params int[] xs) {
    return xs.Sum();
}
Run Code Online (Sandbox Code Playgroud)

然后可以使用您喜欢的任意数量的参数调用它:

Add(1);
Add(1, 2);
Add(1, 2, 3);
Run Code Online (Sandbox Code Playgroud)

但是说我想Add使用ints 1的数组调用.这是可能的以及如何(最好没有反思)?我尝试了以下但他们给出了语法错误(语法纯粹是猜测):

var xs = new[] { 1, 2, 3 };
Add(xs...); // doesn't work; syntax error
Add(params xs); // doesn't work; syntax error
Run Code Online (Sandbox Code Playgroud)

1我的实际用例不同,但我认为这个例子不那么复杂.

Mar*_*ers 11

您的方法需要返回类型:

int Add(params int[] xs) {
    return xs.Sum();
}
Run Code Online (Sandbox Code Playgroud)

要使用数组调用它,只需使用普通语法进行方法调用:

int[] xs = new[] { 1, 2, 3 };
var result = Add(xs);
Run Code Online (Sandbox Code Playgroud)

  • 如果 `Add` 采用 `object[]` 会发生什么?任何类型都可以转换为“object”,那么这不会有歧义吗? (2认同)