1. params
ParamsYou can specify the parameter's method parameter when the number of parameters is variable. In the method declaration, only oneParamsKeyword, which is the last parameter.
Using System;
Class App
{
Public static void UseParams (params object [] list)
{
For (int I = 0; I <list. Length; I ++)
{
Console. WriteLine (list [I]);
}
}
Static void Main ()
{
// The general practice is to first construct an object array and then use this array as a parameter of the method.
Object [] arr = new object [3] {100, 'A', "keywords "};
UseParams (arr );
// After using the params modifier parameter, we can directly use a group of objects as parameters
// Of course, this set of parameters must meet the parameter requirements of the called Method
UseParams (100, 'A', "keywords ");
Console. Read ();
}
}
2. ref and out
RefKeyword to pass Parameters by reference. The effect is that when the control is passed back to the call method, any changes made to the parameters in the method will be reflected in the variable.
- To use the ref parameter, both the method definition and the call method must be explicitly used.RefKeyword.
- Parameters passed to the ref parameter must be initialized first. Unlike out, out parameters do not need to be explicitly initialized before being passed.
- Attributes are not variables, so they cannot be passed as ref parameters.
- While ref and out are processed differently at runtime, they are processed in the same way during compilation. Therefore, if one method uses the ref parameter while the other method uses the out parameter, the two methods cannot be reloaded. For example, from the compilation perspective, the two methods in the following code are exactly the same. If you try to do so, the Code cannot be compiled.
- If one method uses the ref or out parameter, and the other method does not use the two parameters, you can perform the overload.
Example
Static void Main (string [] args)
{
Int I = 0;
RefMethod (ref I); // The ref keyword is also required for calling.
Console. WriteLine ("I =" + I); // The result is I = 1, indicating that the ref keyword can change the value of I.
Int j;
OutMethod (out j); // The out keyword is also required for calling.
Console. WriteLine ("j =" + j); // The result is I = 1, indicating that the ref keyword can change the value of I.
Console. Read ();
}
Public static void RefMethod (ref int I) // The ref keyword is used for the parameter
{
I ++;
}
Public static void OutMethod (out int I) // The out keyword is used for the parameter.
{
I = 0; // The out parameter specifies that the parameter must be initialized in the method body.
I ++;
}