Variable parameters in C # with the keyword params
Codepublic class App { static void Main () { //general use Method Console.WriteLine (ADD (New int32[] {1, 2, 3, 4, 5})) ; Another method of calling Console.WriteLine (ADD (1, 2, 3, 4, 5)); Of course, the number of parameters is variable, but its type is constrained by the Console.WriteLine (ADD (1, 2, 3, 4, 5, 6, 7, 8, 9, ten, one, one, one, and many)); What if the type is variable and the number is variable? The answer to the book is very simple, which is to use the object type //Note down}//<summary>// Use the params keyword </summary> //<param Name= "values" >int[]</param> //<returns>int[] and </ returns> static Int32 Add (params int32[] values) { Int32 sum = 0; for (int x = 0; x < values. Length; x + +) sum + = values[x]; return sum;
Three dots in Java ...
1), can only appear at the end of the parameter list;
2) 、... Between the variable type and the variable name, there are no spaces before and after it can be;
3), when invoking a variable parameter method, the compiler implicitly creates an array for the variable parameter, accessing the mutable parameter in the form of an array in the method body.
public class Varable {
public static void Main (String [] args) {
System.out.println (Add (2,3));
System.out.println (Add (2,3,5));
}
public static int Add (int x,int ... args) {
int sum=x;
for (int i=0;i<args.length;i++) {
Sum+=args[i];
}
return sum;
}
}
Variable parameter comparisons in C # and Java