如您所知,C# 通过 params
关键字支持可变方法:
int Add(params int[] xs) {
return xs.Sum();
}
然后可以使用您喜欢的任意数量的参数调用它:
Add(1);
Add(1, 2);
Add(1, 2, 3);
但是假设我想使用 int
s1 数组调用 Add
。这可能吗以及如何(最好没有反射(reflection))?我尝试了以下但它们给出了语法错误(语法纯粹是猜测):
var xs = new[] { 1, 2, 3 };
Add(xs...); // doesn't work; syntax error
Add(params xs); // doesn't work; syntax error
1 我的实际用例不同,但我认为这个示例不会那么复杂。
最佳答案
你的方法需要一个返回类型:
int Add(params int[] xs) {
return xs.Sum();
}
要用数组调用它,您只需使用方法调用的普通语法:
int[] xs = new[] { 1, 2, 3 };
var result = Add(xs);
关于c# - 将数组解包到方法参数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14983592/