-
out
(C#中的out)
鎖定
示例
- 外文名
- out
- 所屬類別
- 軟件開發 編程語言
- 語 種
- C#
- 用 途
- 聲明 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 Sample Method(out int i) { } public void Sample Method(ref int i) { } }
但是,如果一個方法採用 ref或 out參數,而另一個方法不採用這兩類參數,則可以進行重載,如下所示:
class RefOutOverloadExample { public void SampleMethod(int i) { } public void SampleMethod(out int i) { } }
備註
屬性不是變量,因此不能作為 out參數傳遞。
複製
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 now44 //str1 is now "I've been returned" //str2 is (still) null; } }
- 詞條統計
-
- 瀏覽次數:次
- 編輯次數:19次歷史版本
- 最近更新: 饮水此