C # Params overload method

Source: Internet
Author: User

Generally, you can write multiple overload methods to adapt to different parameters.

If you think there are many parameters that are not certain, you can use an array to store these parameters (parameters of the same data type ).
Of course, for different types of parameters, you can create a structure array with a struct structure to store different parameters, which only affects the performance.

 

Conversion from msdn

 

Parameters declared with the Params modifier are parameter arrays. If a parameter table contains an array of parameters, the array must be at the end of the list and must be a one-dimensional array. For example, the string [] and string [] [] types can be used as parameter arrays, but the string [,] types cannot. It is impossible to combine the Params Modifier with the ref and out modifiers.

In a method call, either of the following two methods is allowed to specify the corresponding parameters for the parameter array:

The parameter assigned to the parameter array can be an expression, and its type can be implicitly converted (section 6.1) to the type of the parameter array. In this case, the parameter array functions exactly the same as the value parameter.
Alternatively, this call can specify zero or multiple parameters for the parameter array. Each parameter is an expression and its type can be implicitly converted (section 6.1) the element type of the parameter array. In this case, this call creates an array instance whose length corresponds to the number of parameters and whose type is the same as that of the parameter array, and initializes the elements of the array instance with the given parameter values, and use the newly created array instance as the real parameter.
Besides allowing variable parameters to be used in a call, the parameter array is equivalent to a value parameter of the same type (section 10.5.1.1.

Example

Using system;
Class Test
{
Static void F (Params int [] ARGs ){
Console. Write ("array contains {0} elements:", argS. Length );
Foreach (int I in ARGs)
Console. Write ("{0}", I );
Console. writeline ();
}
Static void main (){
Int [] arr = {1, 2, 3 };
F (ARR); this array instance is passed as a value parameter, equivalent to F (New int [] {10, 20, 30, 40 });
F (10, 20, 30, 40 );
F (); equivalent to F (New int [] {});
}
}
Generate output

Array contains 3 elements: 1 2 3
Array contains 4 elements: 10 20 30 40
Array contains 0 elements:
The first call to F is to pass the array arr as a value parameter. The second call of F automatically creates a four-element int [] with the given element value and passes the array instance as a value parameter. Similarly, the third call of F creates a zero-element int [] and passes the instance as a value parameter. The second and third calls are equivalent to writing the following code:

F (New int [] {10, 20, 30, 40 });
F (New int [] {});
When performing a overload decision, methods with parameter arrays may be applicable in its normal form or in its extended form (section 7.4.2.1. The above method extension form is available only when the normal method form is not applicable and the method with the same signature has not been declared in the same type as the method extension form.

Example

Using system;
Class Test
{
Static void F (Params object [] ){
Console. writeline ("F (object [])");
}
Static void F (){
Console. writeline ("F ()");
}
Static void F (Object A0, object A1 ){
Console. writeline ("F (object, object )");
}
Static void main (){
F ();
F (1 );
F (1, 2 );
F (1, 2, 3 );
F (1, 2, 3, 4 );
}
}
Generate output

F ();
F (object []);
F (object, object );
F (object []);
F (object []);

* Give priority to the method corresponding to the number of parameters.

In this example, two common methods have been declared in the same class, and their signatures are the same extension form as the method with an array of parameters. Therefore, these extension forms are not taken into account when executing the overload decision, so the first and third method calls will select the regular method. When a method with an array of parameters is declared in a class, it is common to declare some common methods with the same signature as the extension form of the method. In this way, you can avoid configuring the memory space for the Array (if you call an extended method with an array of parameters, you cannot avoid it ).

When the parameter array type is object [], there is a potential ambiguity between the normal method form and the extension form of a single object parameter. The reason for this ambiguity is that object [] itself can be implicitly converted to object. However, this ambiguity does not cause any problems, because it can be solved by inserting a forced conversion as needed.

Example

Using system;
Class Test
{
Static void F (Params object [] ARGs ){
Foreach (Object o in ARGs ){
Console. Write (O. GetType (). fullname );
Console. Write ("");
}
Console. writeline ();
}
Static void main (){
Object [] A = {1, "hello", 123.456 };
Object o =;
F ();
F (object) A); forcibly converted to the object type, rather than the object [] Type
F (o); O is of the object type, not the object [] type.
F (object []) O); forced conversion to object type, rather than object [] Type
}
}
Generate output

System. int32 system. String System. Double
System. object []
System. object []
System. int32 system. String System. Double
In the first and last calls of F, the normal form of F is applicable because there is a conversion from the independent variable type to the parameter type (here, in fact, both are of the object [] type ). Therefore, the normal form of F is selected for the overload decision, and this parameter is passed as a common value parameter. In the second and third calls, the normal form of F is not applicable because there is no conversion from the independent variable type to the parameter type (the type object cannot be implicitly converted to the type object []). However, the extension form of F is applicable, so it is used for heavy-load decision-making. Therefore, both calls create an array with a single element of the object type [] and use the given parameter value (which is itself a reference to an object) initialize the unique element of the array.

 

How to Use Params in C #

Reprinted from: 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. The reference to the array with null or 0 Numbers passed to the last parameter of the method is legal. For example, the following code calls the add method above, the compilation is normal, and the running is normal, and 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 );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.