Ref Parameter
The value parameter is transferred to the method by reference. Special Value Type object.
The comparison before and after use is as follows:
Before using ref
Static void Main (string [] args)
{
Int I = 1;
Console. WriteLine ("before method execution, I address is 0x {0: X}, value is {1}", (uint) & I, I );
TestMethod (I );
Console. WriteLine ("after the method is executed, the address of I is 0x {0: X} and the value is {1}", (uint) & I, I );
Console. ReadLine ();
}
Static void testMethod (int I)
{
I = 2;
Console. WriteLine ("when the method is executed, the I address is 0x {0: X} and the value is {1}", (uint) & I, I );
}
Output:
Before method execution, the I address is 0x4A8E814 and the value is 1.
When the method is executed, the I address is 0x4A8E7B4 and the value is 2.
After the method is executed, the I address is 0x4A8E814 and the value is 1.
The execution process is as follows:
1) Create an int I in the stack. The address is 0x4A8E814 and the value is 1. Create a pointer in the stack and point it to the int above.
2) When executing the method, create a new int in the stack and copy the value of I to the new int. Create a pointer pointing to the copied int.
3) after the method is executed, the newly created int and pointer are discarded (waiting for garbage collection)
Www.2cto.com
After using ref
Unsafe class Program
{
Static void Main (string [] args)
{
Int I = 1;
Console. WriteLine ("before method execution, I address is 0x {0: X}, value is {1}", (uint) & I, I );
TestMethod (ref I );
Console. WriteLine ("after the method is executed, the address of I is 0x {0: X} and the value is {1}", (uint) & I, I );
Console. ReadLine ();
}
Static void testMethod (ref int I)
{
I = 2;
Fixed (int * pI = & (I ))
{
Console. writeLine ("when the method is executed, the I address is 0x {0: X}, the value is {1}", (uint) & (* pI), (uint) * pI );
}
}
}
Output:
Before the method is executed, the I address is 0x4F5EA84 and the value is 1.
When the method is executed, the I address is 0x4F5EA84 and the value is 2.
After the method is executed, the I address is 0x4F5EA84 and the value is 2.
The execution process is as follows:
1) Create an int I in the stack. The address is 0x4A8E814 and the value is 1. Create a pointer in the stack and point it to the int above.
2) create a pointer
3) the newly created pointer is discarded and the I operation is retained.
From heaven on the wall