ref與out的比較:
最近用到了ref和out關鍵字,對於其概念有些遺忘,就又參考MSDN的資料學習了一下,下面是我參考MSDN整理出來的兩者的簡單介紹及比較:
ref與out關鍵字都是使參數通過引用來傳遞的,不同的是ref 要求變量必須在傳遞之前進行初始化,而out 的參數在傳遞之前不需要顯式初始化。
在使用ref或out參數,方法定義和調用方法都必須顯式使用ref或out關鍵字,如:
例1(out):
- class OutExample
- {
- static void Method(out int i)
- {
- i = 44;
- }
- static void Main()
- {
- int value;
- Method(out value);
- // value is now 44
- }
- }
例2(ref):
- class RefExample
- {
- static void Method(ref int i)
- {
- i = 44;
- }
- static void Main()
- {
- int val = 0;
- Method(ref val);
- // val is now 44
- }
- }
儘管 ref 和 out 在運行時的處理方式不同,但它們在編譯時的處理方式是相同的。因此,如果一個方法採用 ref 參數,而另一個方法採用 out 參數,則無法重載這兩個方法。例如,從編譯的角度來看,以下代碼中的兩個方法是完全相同的,因此將不會編譯以下代碼:
- class CS0663_Example
- {
- // compiler error CS0663: "cannot define overloaded
- // methods that differ only on ref and out"
- public void SampleMethod(ref int i) { }
- public void SampleMethod(out int i) { }
- }
但是,如果一個方法採用 ref 或 out 參數,而另一個方法不採用這兩類參數,則可以進行重載,如下所示:
- class RefOutOverloadExample
- {
- public void SampleMethod(int i) { }
- public void SampleMethod(ref int i) { }
- }
示例:
1、out:
當希望方法返回多個值時,聲明 out 方法很有用。使用 out 參數的方法仍然可以將變量用作返回類型,但它還可以將一個或多個對象作爲 out 參數返回給調用方法。此示例使用 out 在一個方法調用中返回三個變量。請注意,第三個參數所賦的值爲 Null。這樣便允許方法有選擇地返回值。
- class OutReturnExample
- {
- static void Method(out int i, out string s1, out string s2)
- {
- i = 44;
- s1 = "I've been returned";
- s2 = null;
- }
- static void Main()
- {
- int value;
- string str1, str2;
- Method(out value, out str1, out str2);
- // value is now 44
- // str1 is now "I've been returned"
- // str2 is (still) null;
- }
- }
2、ref:
按引用傳遞值類型是有用的,但是 ref 對於傳遞引用類型也是很有用的。這允許被調用的方法修改該引用所引用的對象,因爲引用本身是按引用來傳遞的。下面的示例顯示出當引用類型作爲 ref 參數傳遞時,可以更改對象本身。
- class RefRefExample
- {
- static void Method(ref string s)
- {
- s = "changed";
- }
- static void Main()
- {
- string str = "original";
- Method(ref str);
- // str is now "changed"
- }
- }