For example, the following Code :
Copy code The Code is as follows: Class Program
{
Static void main (string [] ARGs)
{
Console. writeline (sum (1 ));
Console. writeline (sum (1, 2, 3 ));
Console. writeline (sum (1, 2, 3, 4, 5 ));
Console. readkey ();
}
Private Static int sum (Params int [] values)
{
Int sum = 0;
Foreach (INT value in values)
Sum + = value;
Return sum;
}
}
A sum method is implemented to receive a group of integers and return their sums. After the parameter values is added with the Params keyword, each element of this set of integers can be listed in the real parameter list during the call, which is very convenient.
Note the following when using the Params Keyword:
1. Params can only be used for one-dimensional arrays. It cannot be used for multi-dimensional arrays or any collection type similar to arrays, such as arraylist and list <t>.
2. The parameter with the Params keyword added must be the last parameter in the parameter list, and only one Params keyword is allowed in the method declaration.
3. Methods Using the Params keyword can be called in three forms:
First, list the elements of the array: sum (, 3), which is also the most common form;
Second, use the array name as the real parameter: sum (New int [] {1, 2, 3}), like an array parameter without the Params keyword }) or int n = new int [] {1, 2, 3}; sum (N );;
Third, the parameter with the Params keyword can be omitted during the call: sum (); // return 0; in this way, sometimes one method overload can be defined, but when int sum () is explicitly defined, the compiler will first call int sum () instead of sum (Params int [] values ). If the Params parameter is omitted, an array with zero element count will still be added in the method, and the efficiency will be slightly checked.
Fourth, Params parameters are not omitted, and null is used instead. The efficiency is slightly higher than that of the third type, because the array is not new internally.