out 參數修飾詞 (C# 參考)

out 關鍵字會導致以傳址 (By Reference) 方式傳遞引數。 這點與 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 OutOverloadExample
{
    public void SampleMethod(int i) { }
    public void SampleMethod(out int i) { i = 5; }
}

屬性並非變數,所以不能當做 out 參數傳遞。

如需傳遞陣列的詳細資訊,請參閱使用 ref 和 out 傳遞陣列 (C# 程式設計手冊)

範例

當您想讓一個方法傳回多個值時,宣告 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;
        }
    }

C# 語言規格

如需詳細資訊,請參閱 C# 語言規格。 語言規格是 C# 語法和用法的決定性來源。

請參閱

參考

C# 關鍵字

方法參數 (C# 參考)

概念

C# 程式設計手冊

其他資源

C# 參考