C# Out關鍵字

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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章