【发布时间】:2009-02-05 17:15:31
【问题描述】:
【问题讨论】:
标签: c#
【问题讨论】:
标签: c#
对于调用者:
对于方法:
所以:
int x;
Foo(ref x); // Invalid: x isn't definitely assigned
Bar(out x); // Valid even though x isn't definitely assigned
Console.WriteLine(x); // Valid - x is now definitely assigned
...
public void Foo(ref int y)
{
Console.WriteLine(y); // Valid
// No need to assign value to y
}
public void Bar(out int y)
{
Console.WriteLine(y); // Invalid: y isn't definitely assigned
if (someCondition)
{
// Invalid - must assign value to y before returning
return;
}
else if (someOtherCondition)
{
// Valid - don't need to assign value to y if we're throwing
throw new Exception();
}
else
{
y = 10;
// Valid - we can return once we've definitely assigned to y
return;
}
}
【讨论】:
最简洁的查看方式:
ref = inout
out = out
【讨论】:
请参阅 MSDN 上的 this 文章。他们都完成了微妙不同的事情,真的。
【讨论】:
Ref 和 out 参数传递模式用于允许方法更改调用者传入的变量。 ref 和 out 之间的区别很微妙但很重要。每种参数传递模式都旨在应用于略有不同的编程场景。 out 和 ref 参数的重要区别在于各自使用的明确赋值规则。
带有out参数的方法的调用者在调用之前不需要分配给作为out参数传递的变量;但是,被调用者需要在返回之前分配给 out 参数。
来源: MSDN
【讨论】:
来自 Alex 提到的 MSDN 文章,
带有out参数的方法的调用者在调用之前不需要分配给作为out参数传递的变量;但是,被调用者需要在返回之前分配给 out 参数。
相比之下,ref 参数被认为是由被调用者最初分配的。因此,被调用者在使用前不需要分配给 ref 参数。
总而言之,在方法内部你可以考虑设置 ref 参数,但不能考虑设置 out 参数——你必须设置这些。 在方法之外,它们的行为应该相同。
【讨论】: