在某些情况下,定义函数时无法预先确定参数的数量。这种情况下,可以使用C#提供的参数数组。参数数组通常用于将未知数量的参数传递给函数。功能。
要使用参数数组,必须使用 params 关键字。
提示:使用参数数组时,既可以将数组作为参数直接传递给函数,也可以使用它来传递一些特定的值作为参数。 。
以下示例显示了以下参数数组的使用:
using System;
namespace it-kiso.com
{
class Demo
{
static void Main(string[] args){
Demo Obj = new Demo();
string str = Obj.getSum(1, 2, 3, 4, 5, 6);
Console.WriteLine(str);
int[] arr = {2, 4, 6, 8, 10};
string str2 = Obj.getSum(arr);
Console.WriteLine(str2);
}
public string getSum(params int[] arr){
int sum = 0;
string str = "";
foreach(int i in arr){
sum += i;
str += "+ " + i + " ";
}
str = str.Trim('+');
str += "= "+sum;
return str;
}
}
} 操作的结果将是:
1 + 2 + 3 + 4 + 5 + 6 = 21
2 + 4 + 6 + 8 + 10 = 30
提示:本示例中使用的 Trim 方法可用于删除字符串左侧和右侧的指定字符。请理解这一点。
《C# params:参数数组》浅显易懂的讲解!您必须观看的 2 个最佳视频
【C#】C#解説 part4 関数、メソッドについて(値渡し、参照渡し、パラメータ修飾子、オプション引数) 【Voiceroid】【プログラミング】
C# tips and tricks 26 – Params keyword in c# | Passing multiple parameters to a method | params




![2021 年如何设置 Raspberry Pi Web 服务器 [指南]](https://i0.wp.com/pcmanabu.com/wp-content/uploads/2019/10/web-server-02-309x198.png?w=1200&resize=1200,0&ssl=1)

