如何在 C# 方法中使用 param 数组传递参数?
csharpprogrammingserver side programming更新于 2025/5/29 9:52:17
声明方法时,您不确定作为参数传递的参数数量。在这种情况下,C# param 数组(或参数数组)会有所帮助。
以下是 param 函数的使用方法 −
public int AddElements(params int[] arr) {
}
以下是完整的 param 函数 − 示例
示例
using System;
namespace Program {
class ParamArray {
public int AddElements(params int[] arr) {
int sum = 0;
foreach (int i in arr) {
sum += i;
}
返回 sum;
}
}
class Demo {
static void Main(string[] args) {
ParamArray app = new ParamArray();
int sum = app.AddElements(300, 250, 350, 600, 120);
Console.WriteLine("总和为:{0}", sum);
Console.ReadKey();
}
}
}
输出
总和为:1620

