您可以在两个上下文中使用out 上下文关键字(每个都是详细信息的链接),作为参数修饰符或在接口和委托中的泛型类型参数声明中。本主题讨论参数修饰符,但您可以查看其他主题以获取有关泛型类型参数声明的信息。
out 关键字导致参数通过引用传递。这类似于ref 关键字,只是ref 要求在传递变量之前对其进行初始化。要使用out 参数,方法定义和调用方法都必须显式使用out 关键字。例如:
C#
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 参数,则方法不能被重载。例如,以下代码将无法编译:
C#
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 参数而另一种方法都不使用,则可以进行重载,如下所示:
C#
class OutOverloadExample
{
public void SampleMethod(int i) { }
public void SampleMethod(out int i) { i = 5; }
}
属性不是变量,因此不能作为out 参数传递。
有关传递数组的信息,请参阅使用 ref 和 out 传递数组(C# 编程指南)。
您不能将ref 和out 关键字用于以下几种方法:
Async methods, which you define by using the async modifier.
Iterator methods, which include a yield return or yield break statement.
例子
当您希望方法返回多个值时,声明out 方法很有用。以下示例使用 out 通过单个方法调用返回三个变量。请注意,第三个参数分配给 null。这使方法能够有选择地返回值。
C#
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;
}
}