C# Parameter array
Sometimes, when declaring a method, you cannot determine the number of arguments to be passed to the function as parameters. C# parameter arrays solve this problem; parameter arrays are typically used to pass an unknown number of arguments to a function.
params keyword
is used as an array, you can call test(a), or you can call test(1,2,3,4).
public 返回类型 方法名称( params 类型名称[] 数组名称 )
Example
The following example demonstrates how to use a parameter array:
Example
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();
}
}
}
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();
}
}
}
When the above code is compiled and executed, it produces the following results:
总和是: 2938other extensions