1. 程式人生 > >在C#中out保留字怎麼使用

在C#中out保留字怎麼使用

表示這個變數要回傳值,最簡單的應用是除法,比如你需要一個除法方法,同時得到餘數和商,但是普通的方法只能得到一個返回值,這個時候就可以使用Out引數,把另一個值返回。
比如,你定義了一個方法int a(int b,out int c),它除了能得到返回值外,還可以在方法裡對C進行賦值,這樣你就可以使用C的值了。

①ref要求引數必須被初始化,out沒有這個要求。  
  ②ref引數可以被修改,也可以不被修改,但是out必須被賦值或者修改。  
  ③ref引數值可以在任何時候被呼叫引數使用,而out引數值只能在被賦值後才可以被使用。

1,明確語義:out在呼叫函式裡必須賦值,語法檢查裡能確保這個變數確實被函式修改了。  
  2,相關性:out在呼叫函式前的賦值是被忽略的,也就是說與方法呼叫前的值無關,所以只要宣告過就可以了。   

方法引數上的 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 staticvoid outTest(outint x, outint y)
 7  {//離開這個函式前,必須對x和y賦值,否則會報錯。
 8 //y = x;
 9 //上面這行會報錯,因為使用了out後,x和y都清空了,需要重新賦值,即使呼叫函式前賦過值也不行
10   x =1;
11   y =2;
12  }
13 staticvoid refTest(refint x, refint y)
14  {
15   x =1;
16   y = x;
17  }
18 19 20 staticpublicvoid OutArray(outint[] myArray)
21  {
22 // Initialize the array:23      myArray =newint[5] { 12345 };
24  }
25 publicstaticvoid FillArray(refint[] arr)
26  {
27 // Create the array on demand:28 if (arr ==null)
29          arr =newint[10];
30 // Otherwise fill the array:31      arr[0=123;
32      arr[4=1024;
33  }
34 35 36 publicstaticvoid Main()
37  {
38 //out test39 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 test48 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 = { 12345 };
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 }

執行結果 如下: