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 you direct the memory address to a new object in the method,
After the method is completed, the modifications made in the method will be discarded.
1 class Program
2
3 {
4
5 static void Main (string [] args)
6
7 {
8
9 Employee myE = new Employee () {id = 4 };
10
11 Console. WriteLine ("initialization:" + myE. id );
12
13 testMethod (myE );
14
15 Console. WriteLine ("Exit method:" + myE. id );
16
17 Console. ReadLine ();
18
19}
20
21 static void testMethod (Employee myE)
22
23 {
24
25 // myE. id = 5;
26
27 myE = new Employee () {id = 5 };
28
29 Console. WriteLine ("changed to:" + myE. id );
30
31}
32
33}
34
35 class Employee
36
37 {
38
39 public int id {get; set ;}
40
41}
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,
It is passed by ref reference, but sometimes it will 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.
1 static string Combine (params string [] paths)
2
3 {
4
5 string result = string. Empty;
6
7 foreach (string path in paths)
8
9 {
10
11 result = System. IO. Path. Combine (result, path );
12
13}
14
15 return result;
16
17}
18
19 static void test ()
20
21 {
22
23 // call method 1 and enter it directly. If you do not use the params prefix, you cannot use this method.
24
25 string path1 = Combine ("","","");
26
27 // call method 2, string array. This method can also be used without the params prefix.
28
29 string path2 = Combine (new string [] {"", "", ""});
30
31}
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 follow-up kiddies