Static Void Main ()
{
Console. writeline (test ( 1 )); // The first parameter is passed, and the second parameter uses the default
Console. writeline (test ( 2 , " Operators " )); // We have defined both parameters.
Console. writeline (Params ( " Qq " )); // The second parameter is passed new int [0];
Console. writeline (Params ( " Qq " , Null )); // The same effect as above, but it is more efficient because no array is allocated;
Console. writeline (Params ( " Qq " , 1 , 2 , 3 , 4 ));
Console. writeline (Params ( " TT " , 1 , 2 )); // Check that all methods with the specified name and paramarry attribute are not applied to the parameter. If a matching method is found, a call to this method is generated.
// If not, the system checks whether the paramarry attribute method is applied.
Console. writeline (Params ( " Nn " , 1 , 2 , 4 , 5 , 6 )); // Call the static string Params (string S, int I = 1, Params int [] OBJ) method to match the parameters of non-optional methods.
Console. readkey ();
}
Static String Test ( Int I, String S = " Default " ) // Optional parameters must appear after all required parameters
{
Return S;
}
Static String Params ( String S, Params Int [] I) // Variable parameters must be the last parameter in the form parameter list.
{
If (I! = Null )
{
For ( Int T = 0 ; T <I. length; t ++)
{
S + = I [T]. tostring ();
}
}
Return S;
}
Static String Params ( String S, Int I = 1 , Params Int [] OBJ) // However, the default parameter can be followed by the array parameter (Params parameter ),
// In fact, the Params parameter can only be the last declared parameter under any circumstances. Another restriction of the default parameter is that the specified default value must be a constant.
{
Foreach ( Object O In OBJ)
{
S + = O. tostring ();
}
Return S;
}
Static String Params ( String S, Int I, Int T)
{
Return S + I. tostring () + T. tostring ();
}
}
When using default parameters, if the parameter is identified by the ref or out keyword, the default value cannot be set, because there is no way to pass a meaningful default value for these parameters.
When a variable number of parameters is called, some extra performance losses will occur (unless null is explicitly passed). After all, the array object must be allocated on the stack and the array element must be initialized, in addition, the Array Memory must eventually be garbage collected. To reduce performance loss, you can consider defining several overloaded versions that do not use the Params keyword.
Loading editor...