C# - 参数数组
有时,在声明方法时,您不确定作为参数传递的参数数量。在这种情况下,C# 参数数组(或参数数组)会有所帮助。
以下示例演示了这一点 -
using System;
namespace ArrayApplication {
class ParamArray {
public int AddElements(params int[] arr) {
int sum = 0;
foreach (int i in arr) {
sum += i;
}
return sum;
}
}
class TestClass {
static void Main(string[] args) {
ParamArray app = new ParamArray();
int sum = app.AddElements(512, 720, 250, 567, 889);
Console.WriteLine("The sum is: {0}", sum);
Console.ReadKey();
}
}
}
当编译并执行上述代码时,它会产生以下结果 -
The sum is: 2938

csharp_arrays.html