1. The role of the params keyword
(1), use the params keyword to specify a method parameter that has a variable number of methods parameters.
(2), you can send a comma-separated list of parameters of the type specified in the parameter declaration or an array of parameters of the specified type. You can also not send parameters. If no parameters are sent, the params length of the list is zero.
(3), no other parameters are allowed after the keyword in the method declaration params , and only one keyword is allowed in the method declaration params .
The code is as follows:
static void Main (string[] args) { int[] Myintarray = {5, 6, 7, 8, 9}; USEPARAM1 (Myintarray); Object[] Myobjarray = {2, ' B ', "Test", "again"}; USEPARAM2 (Myobjarray);} static void UseParam1 (params int[] args) {for (int i = 0; i < args. Length; i++) { Console.WriteLine (Args[i] + "...");} } static void UseParam2 (params object[] objs) {for (int i = 0; i < Objs. Length; i++) { Console.WriteLine (Objs[i] + "");} }
Output:
2. Summary and Analysis
(1) When the type of the parameter is defined as Param int[] args, then the Useparam method receives a variable-length parameter array of type int, note: Only one-dimensional, not two-dimensional, if the two-dimensional chaos
Therefore, there are two ways to invoke the Useparam method:
I, the code is as follows:
Useparam (1,2,3,4,5);
II, the code is as follows:
Int[] args={1,2,3,4,5}; Useparam (args);
(2) When the type of the parameter is defined as Param object[] args, this is the Useparam to receive a variable-length object type parameter array, note: Can only be one-dimensional, not two-dimensional, if the two-dimensional chaos
Therefore, there are two ways to invoke the Useparam method:
I, the code is as follows:
Useparam (1, "2", True, "a")
II, the code is as follows:
Object[] args={1,2, "3", false,5}; Useparam (args);
Reprinted from: http://www.cnblogs.com/GreenLeaves/p/6756637.html
C # params keyword