ref 關鍵字使參數按引用傳遞。其效果是,當控制權傳遞迴調用方法時,在方法中對參數所做的任何更改都將反映在該變量中。若要使用 ref 參數,則方法定義和調用方法都必須顯式使用 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 不同,out 的參數在傳遞之前不需要顯式初始化。(請參見 out。)
儘管 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) { } }
屬性不是變量,因此不能作爲 ref 參數傳遞。
有關傳遞數組的信息,請參見使用 ref 和 out 傳遞數組。
按引用傳遞值類型(如上所示)是有用的,但是 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" } }
out 關鍵字會導致參數通過引用來傳遞。這與 ref 關鍵字類似,不同之處在於 ref 要求變量必須在傳遞之前進行初始化。若要使用 out 參數,方法定義和調用方法都必須顯式使用 out 關鍵字。例如:
class OutExample { static void Method(out int i) { i = 44; } static void Main() { int value; Method(out value); // value is now 44 } }
儘管作爲 out 參數傳遞的變量不需要在傳遞之前進行初始化,但需要調用方法以便在方法返回之前賦值。
ref 和 out 關鍵字在運行時的處理方式不同,但在編譯時的處理方式相同。因此,如果一個方法採用 ref 參數,而另一個方法採用 out 參數,則無法重載這兩個方法。例如,從編譯的角度來看,以下代碼中的兩個方法是完全相同的,因此將不會編譯以下代碼:
class CS0663_Example { // compiler error CS0663: "cannot define overloaded // methods that differ only on ref and out" public void SampleMethod(out int i) { } public void SampleMethod(ref int i) { } }
但是,如果一個方法採用 ref 或 out 參數,而另一個方法不採用這兩類參數,則可以進行重載,如下所示:
class RefOutOverloadExample { public void SampleMethod(int i) { } public void SampleMethod(out int i) { } }
屬性不是變量,因此不能作爲 out 參數傳遞。
有關傳遞數組的信息,請參見使用 ref 和 out 傳遞數組。
當希望方法返回多個值時,聲明 out 方法很有用。使用 out 參數的方法仍然可以將變量用作返回類型(請參見 return),但它還可以將一個或多個對象作爲 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; } }