C# Parameter Arrays
Sometimes, when declaring a method, you cannot determine the number of arguments to pass to the function. C# parameter arrays solve this problem; they are typically used to pass an unknown number of arguments to a function.
The params Keyword
When using an array as a formal parameter, C# provides the params keyword so that when calling a method with an array parameter, you can pass either an array argument or a set of array elements. The syntax for params is:
public 返回类型 方法名称( params 类型名称[] 数组名称 )
Example
The following example demonstrates how to use parameter arrays:
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
(
)
;
}
}
}
When the code above is compiled and executed, it produces the following result:
总和是: 2938
C# Arrays