如何在 C# 方法中使用 param 数组传递参数?
声明一个方法时,你不能肯定作为参数传递的实参数量。此时 C# param 数组(或参数数组)就能派上用场。
以下是如何使用 param −
public int AddElements(params int[] arr) {
}以下是完整示例 −
示例
using System;
namespace Program {
class ParamArray {
public int AddElements(params int[] arr) {
int sum = 0;
foreach (int i in arr) {
sum += i;
}
return sum;
}
}
class Demo {
static void Main(string[] args) {
ParamArray app = new ParamArray();
int sum = app.AddElements(300, 250, 350, 600, 120);
Console.WriteLine("The sum is: {0}", sum);
Console.ReadKey();
}
}
}输出
The sum is: 1620
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP