C # parameter array
Sometimes, when declaring a method, you can not determine the number of parameters to be passed to the function as a parameter. C # parameter array to solve this problem, the array parameter is usually used to pass an unknown number of arguments to the function.
params keyword
When using an array as a parameter, C # provides params keyword, make calls when the array parameter method, both can pass an array of arguments, you can pass only a set of arrays. params using the format:
public 返回类型 方法名称( params 类型名称[] 数组名称 )
Examples
The following example demonstrates how to use an array of parameters:
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 ( "Total is: {0}", sum); Console.ReadKey (); } } }
When the above code is compiled and executed, it produces the following results:
The sum is: 2938