out 参数修饰符(C# 参考)

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 参数传递的变量不必在传递之前进行初始化,但被调用的方法需要在返回之前赋一个值。

尽管 refout 关键字会导致不同的运行时行为,但在编译时并不会将它们视为方法签名的一部分。因此,如果两个方法唯一的区别是:一个接受 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) { }
}

但是,如果一个方法采用 refout 参数,而另一个方法不采用这两类参数,则可以进行重载,如下所示:

class OutOverloadExample
{
    public void SampleMethod(int i) { }
    public void SampleMethod(out int i) { i = 5; }
}

属性不是变量,因此不能作为 out 参数传递。

有关传递数组的信息,请参见使用 ref 和 out 传递数组(C# 编程指南)

不能为以下方法使用 refout 关键字:

  • 异步方法,或者使用 async 修饰符,定义。

  • 迭代器方法,包括一个 将返回yield break 语句。

当希望方法返回多个值时,声明 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# 参考)