有简明的解释吗?
也在以下问题中回答: .NET中ref和out参数的区别
对于调用者:
对于方法:
因此:
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 = 输入输出
out = 输出
Ref和out参数传递模式用于允许方法修改调用者传入的变量。ref和out之间的区别微妙但重要。每种参数传递模式都设计用于稍微不同的编程场景。out和ref参数之间的重要区别在于它们使用的明确赋值规则。
调用一个带有out参数的方法的调用者在调用之前不需要为传递的变量分配值;然而,被调用者在返回之前必须为out参数分配值。
来源: MSDN
根据Alex提到的MSDN文章,
调用一个带有out参数的方法的调用者在调用之前不需要为传递的变量分配值;但是,在返回之前,被调用者必须为out参数分配值。
相比之下,ref参数被认为是由被调用者最初分配的。因此,在使用之前,被调用者不需要为ref参数分配值。
因此,总结一下,在方法内部,您可以将ref参数视为已设置,但不是out参数-您必须设置这些参数。 在方法外部,它们应该表现相同。