Languages like C and C provide many means to create and use a function that accepts unprofitable parameters, the most typical example is the Printf () function:
INT Printf (Char * Format, ...); / / omitted number indicates that the number of parameters is not
Use this function very simple:
Printf ("Hello, WORLD / N");
Printf ("THE SUM OF% D and% D IS% D / N", A, B, A B);
However, using these languages to create such functions must rely on a series of pre-defined macros, and often does not have intuitive and elegant.
By using parameter arrays, C # provides an elegant solution to this problem. The parameter array is a one-dimensional array that appears in the parameter list as the last parameter of the method:
Public String Concat (String Separator, params string [] strings)
{
String result = "";
For (int i = 0; i { IF (i> 0) Result = separator; Result = strings [i]; } Return Result; } The above method is used to connect some strings into a string, which can be called in two different ways: 1) Use an array instance to pass as a parameter to a method: String [] name = {"Anders", "eric", "scott", "duncan"}; MessageBox.show (Concat (" ", Names) "= Great Team"); 2) Parameters to use 0 or more types to pass to the method: MessageBox.show (Concat (" ", "Anders", "Eric", "Scott", " Duncan ") " = great team "); When you call the method using the second method, you will use these types of compatible parameters (in the above example, all parameters behind the first parameter) create an array, and then transmit this parameter array as a real argument to the method. . It can be seen from this point: in fact, the two methods above pass the same mechanism is exactly the same, but the expression technique is different. Thanks to the .NET unified type system (all types are inherited from Object, so you can use the unified process of the type of polymorphism, you can define the object [] as any type of emission name as a parameter array, Use specific type calls when calling methods: Public int su.tegers (params object [] list) { // sum all the integers incn INT SUM = 0; Foreach (Object O IN LIST) IF (o.gettype () == TypeOf (int)) SUM = (int) O; Return SUM; }