C # When the value type and reference type are passed as method parameters, they can both be called "value", but the "value" here refers to something different.
When a method parameter is of the value type, the method passes the value itself.
When the parameter of a method is of the reference type, the method passes the address of the application type reference, that is, the value of the reference type address on the stack.
Example of passing a reference type as a parameter
Code
static void Main()
{
ArgsRef abf = new ArgsRef();
AddRef(abf);
Console.WriteLine(abf.i);
Console.Read();
}
private static void AddRef(ArgsRef abf)
{
//abf = new ArgsRef();
abf.i = 20;
Console.WriteLine(abf.i);
}
class ArgsRef
{
public int i = 10;
}
Assume that in the main method, argsref abf = new argref (); the stack address of abf is 0x10; then, addref (abf) is used in the process of passing the method ); it is actually a transfer address pointing, and this address pointing is also a copy of the original address.
Strictly speaking, it is also a "value" transfer, similar to abf = 0x10;
When the annotation in the demo is removed: In the addref method, if you execute abf = new argsref () Again, the abf address is changed, the new address is assigned to abf, which is assumed to be 0x11. In the method body
Abf is actually the object pointed to by 0x11. In the main method, the abf address in console. writeline (abf. I) is still 0x10,
Because the method is used to copy the passed address when passing the reference parameter, a copy of the passed value is consistent when passing the value type.
Therefore:
In the above example, if the first line of the method addref is commented out, the output result in the main method is: 20, 20; if the comment is removed, the output result is: 20, 10.