您的位置:首页 > 编程语言 > C#

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

2015-04-22 08:17 197 查看
Visual Studio 2013
其他版本





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 修饰符,定义。
迭代器方法,包括一个 将返回 或 yield break 语句。

示例

当希望方法返回多个值时,声明 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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C# out 参数类型