Turn: http://blog.csdn.net/genispan/article/details/5466975
To declare a method as a method that can accept variable quantity parameters, we can use the Params keyword to declare an array, as shown below:
Public static int32add (Params int32 [] values)
{
Int32 sum = 0;
For (int32 x = 0; x <values. length; X ++)
{
Sum + = values [x];
}
Return sum;
}
Only the last parameter of the method can mark Params. This parameter must identify a one-dimensional array, but the type is not limited. It is legal to reference an array with null or zero numbers passed to the last parameter of the method, as shown belowCodeCall the add method above to compile normally and run normally. The result is 0 as expected:
Public static void main ()
{
Console. writeline (add ());
}
The following describes how to compile a method that can accept any number or type of parameters. That is, you can change int32 of the above method to object:
Public static void main ()
{
Displaytypes (new object (), new random (), "string", 10 );
}
Public static void displaytypes (Params object [] objects)
{
Foreach (Object o in objects)
{
Console. writeline (O. GetType ());
}
}
Output:
System. Object
System. Random
System. String
System. int32
Note that calling methods that can accept variable quantity parameters will cause some performance loss, because the array is allocated on the heap and the elements of the array have to be initialized, the Array Memory has to be recycled by the garbage collector. To reduce this unnecessary performance loss, we want to define several overload methods without the Params keyword, such as system. the Concat method of the string class is as follows:
Public static string Concat (Object arg0 );
Public static string Concat (Params object [] ARGs );
Public static string Concat (Params string [] values );
Public static string Concat (Object arg0, object arg1 );
Public static string Concat (string str0, string str1 );
Public static string Concat (Object arg0, object arg1, object arg2 );
Public static string Concat (string str0, string str1, string str2 );
Public static string Concat (Object arg0, object arg1, object arg2, object arg3 );
Public static string Concat (string str0, string str1, string str2, string str3);