方法參數上的 out 方法參數關鍵字使方法引用傳遞到方法的同一個變數。
當控制傳遞迴調用方法時,在方法中對參數所做的任何更改都將反映在該變數中。
當希望方法返回多個值時,聲明 out 方法非常有用。
使用 out 參數的方法仍然可以返回一個值。一個方法可以有一個以上的 out 參數。
若要使用 out 參數,必須將參數作為 out 參數顯式傳遞到方法。out 參數的值不會傳遞到 out 參數。
不必初始化作為 out 參數傳遞的變數。然而,必須在方法返回之前為 out 參數賦值。
屬性不是變數,不能作為 out 參數傳遞。
方法參數上的 ref 方法參數關鍵字使方法引用傳遞到方法的同一個變數。
當控制傳遞迴調用方法時,在方法中對參數所做的任何更改都將反映在該變數中。
若要使用 ref 參數,必須將參數作為 ref 參數顯式傳遞到方法。
ref 參數的值被傳遞到 ref 參數。 傳遞到 ref 參數的參數必須最先初始化。
將此方法與 out 參數相比,後者的參數在傳遞到 out 參數之前不必顯式初始化。
屬性不是變數,不能作為 ref 參數傳遞。
兩者都是按地址傳遞的,使用後都將改變原來的數值。
ref可以把參數的數值傳遞進函數,但是out是要把參數清空
就是說你無法把一個數值從out傳遞進去的,out進去後,參數的數值為空白,所以你必須初始化一次。
兩個的區別:ref是有進有出,out是只出不進。
代碼執行個體如下:
1 namespace TestOutAndRef
2 {
3 class TestApp
4 {
5
6 static void outTest(out int x, out int y)
7 {//離開這個函數前,必須對x和y賦值,否則會報錯。
8 //y = x;
9 //上面這行會報錯,因為使用了out後,x和y都清空了,需要重新賦值,即使調用函數前賦過值也不行
10 x = 1;
11 y = 2;
12 }
13 static void refTest(ref int x, ref int y)
14 {
15 x = 1;
16 y = x;
17 }
18
19
20 static public void OutArray(out int[] myArray)
21 {
22 // Initialize the array:
23 myArray = new int[5] { 1, 2, 3, 4, 5 };
24 }
25 public static void FillArray(ref int[] arr)
26 {
27 // Create the array on demand:
28 if (arr == null)
29 arr = new int[10];
30 // Otherwise fill the array:
31 arr[0] = 123;
32 arr[4] = 1024;
33 }
34
35
36 public static void Main()
37 {
38 //out test
39 int a,b;
40 //out使用前,變數可以不賦值
41 outTest(out a, out b);
42 Console.WriteLine("a={0};b={1}",a,b);
43 int c=11,d=22;
44 outTest(out c, out d);
45 Console.WriteLine("c={0};d={1}",c,d);
46
47 //ref test
48 int m,n;
49 //refTest(ref m, ref n);
50 //上面這行會出錯,ref使用前,變數必須賦值
51
52 int o=11,p=22;
53 refTest(ref o, ref p);
54 Console.WriteLine("o={0};p={1}",o,p);
55
56
57
58 int[] myArray1; // Initialization is not required
59
60 // Pass the array to the callee using out:
61 OutArray(out myArray1);
62
63 // Display the array elements:
64 Console.WriteLine("Array1 elements are:");
65 for (int i = 0; i < myArray1.Length; i++)
66 Console.WriteLine(myArray1[i]);
67
68 // Initialize the array:
69 int[] myArray = { 1, 2, 3, 4, 5 };
70
71 // Pass the array using ref:
72 FillArray(ref myArray);
73
74 // Display the updated array:
75 Console.WriteLine("Array elements are:");
76 for (int i = 0; i < myArray.Length; i++)
77 Console.WriteLine(myArray[i]);
78 }
79 }
80
81 }