Declare a variable number of parameters:
CopyCodeThe Code is as follows: static int add (Params int [] values)
{
Int sum = 0;
If (value! = NULL)
{
For (INT x = 0; x <values. length; X ++)
Sum + = values [x];
}
Return sum;
}
Except Params, this method is a common method that accepts the int array and returns the sum of all items in the group.
We can call: add (New int [] {1, 2, 3 });
However, reading is not very high, and we hope to be more concise:
Add (1, 2, 3 );
In this case, the Params keyword can be compiled and run.
Params can only be applied to the last of the method parameters.
When the C # compiler finds add (, 3), it first looks for the matching method of add (int I, Int J, int K,
If yes, call it. If no, check whether there is a method defined as add (Params int [] values,
If yes, save 1, 2, and 3 to an array, and then call the add (INT [] values) method.
It also shows that CLR does not know anything about the Params keyword. Params is only provided to the C # compiler.