REF和OUT關鍵字的介紹

       最近用到了ref和out關鍵字,對於其概念有些遺忘,就又參考MSDN的資料學習了一下,下面是我參考MSDN整理出來的兩者的簡單介紹及比較:
refout的比較:

refout關鍵字都是使參數通過引用來傳遞的,不同的是ref 要求變量必須在傳遞之前進行初始化,而out 的參數在傳遞之前不需要顯式初始化。

在使用refout參數,方法定義和調用方法都必須顯式使用refout關鍵字,如:

1out):

 

  1. class OutExample  
  2. {  
  3.     static void Method(out int i)  
  4.     {  
  5.         i = 44;  
  6.     }  
  7.     static void Main()  
  8.     {  
  9.         int value;  
  10.         Method(out value);  
  11.         // value is now 44  
  12.     }  
  13. }  

2ref):

  1. class RefExample  
  2.  {  
  3.      static void Method(ref int i)  
  4.      {  
  5.          i = 44;  
  6.      }  
  7.  
  8.     static void Main()  
  9.      {  
  10.          int val = 0;  
  11.          Method(ref val);  
  12.          // val is now 44  
  13.      }  
  14.  }  
  15.  

儘管 ref  out 在運行時的處理方式不同,但它們在編譯時的處理方式是相同的。因此,如果一個方法採用 ref 參數,而另一個方法採用 out 參數,則無法重載這兩個方法。例如,從編譯的角度來看,以下代碼中的兩個方法是完全相同的,因此將不會編譯以下代碼:

 

  1. class CS0663_Example   
  2.  
  3. {  
  4.  
  5.     // compiler error CS0663: "cannot define overloaded   
  6.  
  7.     // methods that differ only on ref and out"  
  8.  
  9.     public void SampleMethod(ref int i) {  }  
  10.  
  11.     public void SampleMethod(out int i) {  }  
  12.  
  13. }  
  14.  

但是,如果一個方法採用 ref  out 參數,而另一個方法不採用這兩類參數,則可以進行重載,如下所示:

  1. class RefOutOverloadExample  
  2. {  
  3.     public void SampleMethod(int i) {  }  
  4.     public void SampleMethod(ref int i) {  }  

 

示例:

1out

當希望方法返回多個值時,聲明 out 方法很有用。使用 out 參數的方法仍然可以將變量用作返回類型,但它還可以將一個或多個對象作爲 out 參數返回給調用方法。此示例使用 out 在一個方法調用中返回三個變量。請注意,第三個參數所賦的值爲 Null。這樣便允許方法有選擇地返回值。

 

  1. class OutReturnExample  
  2. {  
  3.     static void Method(out int i, out string s1, out string s2)  
  4.     {  
  5.         i = 44;  
  6.         s1 = "I've been returned";  
  7.         s2 = null;  
  8.     }  
  9.     static void Main()  
  10.     {  
  11.         int value;  
  12.         string str1, str2;  
  13.         Method(out value, out str1, out str2);  
  14.         // value is now 44  
  15.         // str1 is now "I've been returned"  
  16.         // str2 is (still) null;  
  17.     }  
  18. }  

2ref

按引用傳遞值類型是有用的,但是 ref 對於傳遞引用類型也是很有用的。這允許被調用的方法修改該引用所引用的對象,因爲引用本身是按引用來傳遞的。下面的示例顯示出當引用類型作爲 ref 參數傳遞時,可以更改對象本身。

  1. class RefRefExample  
  2. {  
  3.     static void Method(ref string s)  
  4.     {  
  5.         s = "changed";  
  6.     }  
  7.  
  8.     static void Main()  
  9.     {  
  10.         string str = "original";  
  11.         Method(ref str);  
  12.         // str is now "changed"  
  13.     }  
  14. }  
  15.  

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章