.NET中ref和out参数的区别是什么?在什么情况下,一个会比另一个更有用?一个可以使用而另一个不能使用的代码片段是什么?


当前回答

ref变量在传入之前需要初始化。 需要在函数实现中设置out变量 输出参数可以被认为是额外的返回变量(不是输入) Ref参数可以看作是输入变量和输出变量。

其他回答

An out parameter is a ref parameter with a special Out() attribute added. If a parameter to a C# method is declared as out, the compiler will require that the parameter be written before it can be read and before the method can return. If C# calls a method whose parameter includes an Out() attribute, the compiler will, for purposes of deciding whether to report "undefined variable" errors, pretend that the variable is written immediately before calling the method. Note that because other .net languages do not attach the same meaning to the Out() attribute, it is possible that calling a routine with an out parameter will leave the variable in question unaffected. If a variable is used as an out parameter before it is definitely assigned, the C# compiler will generate code to ensure that it gets cleared at some point before it is used, but if such a variable leaves and re-enters scope, there's no guarantee that it will be cleared again.

Out和ref是完全相同的,除了Out变量在发送到深渊之前不需要初始化。我没有那么聪明,我从MSDN库抄袭了:)。

然而,更明确地说,修饰符的含义是,如果您在代码中更改了该变量的引用,out和ref将导致调用变量也更改引用。在下面的代码中,一旦newGuy从doStuff调用中返回,ceo变量将是它的引用。如果不是为了ref(或out),引用就不会被改变。

private void newEmployee()
{
    Person ceo = Person.FindCEO();
    doStuff(ref ceo);
}

private void doStuff(ref Person employee)
{
    Person newGuy = new Person();
    employee = newGuy;
}

Ref可能会在null时阻塞,因为它可能期望修改一个现有对象。Out需要null,因为它返回一个新对象。

在函数中不需要设置Ref形参,而out形参必须在退出函数之前绑定到一个值。传递出去的变量也可以在没有初始化的情况下传递给函数。

ref变量在传入之前需要初始化。 需要在函数实现中设置out变量 输出参数可以被认为是额外的返回变量(不是输入) Ref参数可以看作是输入变量和输出变量。