I. general parameter transfer method
In c #, unless the ref or out prefix is used, all parameters are passed through values. The stack data of the variable is completely copied to the target parameter. There are three scenarios:
1. variables of the reference type only contain the memory address of the object. The memory address instead of the object itself will be copied, so modifications to the underlying object will be retained. If the memory address inside the method points to a new object, the modifications made in the method after the method ends will be discarded (the original pointer still points to the original object, and the method parameter points to the new object, ).
Class Program
{
Static void Main (string [] args)
{
Employee myE = new Employee () {id = 4 };
Console. WriteLine ("initialization:" + myE. id );
TestMethod (myE );
Console. WriteLine ("Exit method:" + myE. id );
Console. ReadLine ();
}
Static void testMethod (Employee myE)
{
// MyE. id = 5;
MyE = new Employee () {id = 5 };
Console. WriteLine ("changed to:" + myE. id );
}
}
Class Employee
{
Public int id {get; set ;}
}
The program output is
2. A Value Type object contains actual data, and a copy of the data itself is passed to the method. Modifications to a value type object are discarded after the method ends.
3. the String type is treated as the value type in actual use.
Ii. Special parameter transfer methods
1. ref Parameters
Purpose: force the value parameter to be transferred to the method through reference.
2. out parameters
Purpose: Output multiple values in a function without parameter initialization. Implicit ref.
C # The variable must be initialized before being referenced. Although they can be initialized with meaningless values before being passed and passed with ref references, it may sometimes cause confusion. With out, you can use parameters without initialization, which is more logical.
3. variable number of params Parameters
Purpose: automatically convert parameters into arrays.
There are two call methods, as shown in the example.
Static string Combine (params string [] paths)
{
String result = string. Empty;
Foreach (string path in paths)
{
Result = System. IO. Path. Combine (result, path );
}
Return result;
}
Static void test ()
{
// Call method 1 and enter it directly. If you do not use the params prefix, you cannot use this method.
String path1 = Combine ("","","");
// Call method 2, string array, which can be used without the params prefix
String path2 = Combine (new string [] {"", "", ""});
}
Iii. Considerations for passing parameters:
1. attributes are not variables, so they cannot be passed to out or ref parameters.
2. Unless the out prefix is used, all parameters must be initialized before use.
3. The out parameter must be assigned a value before the function ends. The value can be null.
From heaven on the wall