out(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 参数传递的变量无需在传递之前初始化,调用方法仍要求在方法返回之前赋值。

尽管 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 returnyield 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# 参考