When passing a real parameter to a method, the corresponding form parameter will be initialized with a copy of the real parameter, no matter the form parameter is a value type (such as int), can be empty type (int ?), Or the reference type, which is true. That is, any modifications made within the method will not affect the value of the real parameter. For example, changes to the reference type and method only change the referenced data, but the real parameter itself does not change and it still references the same object.
The Code is as follows:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Namespace ref_out
{
Class Program
{
Static void Main (string [] args)
{
Int I = 8;
Console. WriteLine (I );
DoIncrease (I );
Console. WriteLine (I );
}
Static void DoIncrease (int)
{
A ++;
}
}
} The running result is as follows:
If the ref keyword is used, any operation applied to the Vector parameter is also applied to the real parameter, because the shape parameter and the real parameter reference the same object. PS: both real parameters and form parameters must be prefixed with the ref keyword.
The Code is as follows:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Namespace ref_out
{
Class Program
{
Static void Main (string [] args)
{
Int I = 8;
Console. WriteLine (I); // 8
DoIncrease (ref I); // you must add ref before the real parameter.
Console. WriteLine (I); // 9 // ref keyword to apply the action of the parameter to the real Parameter
}
Static void DoIncrease (ref int a) // ref must be added before the Parameter
{
A ++;
}
}
} The running result is as follows:
The ref parameter must be initialized before it is used. Otherwise, it cannot be compiled.
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Namespace ref_out
{
Class Program
{
Static void Main (string [] args)
{
Int I; // ref real parameter is not initialized, so the program cannot be compiled
Console. WriteLine (I );
DoIncrease (ref I );
Console. WriteLine (I );
}
Static void DoIncrease (ref int)
{
A ++;
}
}
}
Sometimes we want to initialize the parameter by the method itself. In this case, the out parameter can be used.
The Code is as follows:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Namespace ref_out
{
Class Program
{
Static void Main (string [] args)
{
Int I; // No Initialization
// Console. WriteLine (I); // here I is not initialized, compilation Error
DoIncrease (out I); // use a method to assign an initial value to the real Parameter
Console. WriteLine (I );
}
Static void DoIncrease (out int)
{
A = 8; // initialize IN THE METHOD
A ++; // a = 9
}
}
}
The running result is as follows: