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


当前回答

out在c# 7中获得了新的更简洁的语法 https://learn.microsoft.com/en-us/dotnet/articles/csharp/whats-new/csharp-7#more-expression-bodied-members 更令人兴奋的是c# 7的元组增强,这是一个比使用ref和out更优雅的选择。

其他回答

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:

在c#中,一个方法只能返回一个值。如果希望返回多个值,可以使用out关键字。out修饰符返回为引用返回。最简单的答案是使用关键字“out”从方法中获取值。

您不需要在调用函数中初始化该值。 必须在被调用的函数中赋值,否则编译器将报错。

ref:

在c#中,当你将一个值类型,如int, float, double等作为参数传递给方法参数时,它是按值传递的。因此,如果修改形参值,它不会影响方法调用中的实参。但是,如果您用“ref”关键字标记参数,它将反映在实际的变量中。

在调用函数之前,需要初始化变量。 为方法中的ref参数赋值不是强制的。如果不更改值,为什么需要将其标记为“ref”?

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

它们有微妙的不同。

out形参在传递给方法之前不需要由被调用方初始化。因此,任何带有out参数的方法

在为参数赋值之前无法读取该参数 必须在返回之前给它赋值吗

这用于需要覆盖其参数的方法,而不管其先前的值如何。


ref形参在传递给方法之前必须由被调用方初始化。因此,任何带有ref参数的方法

在赋值之前可以检查值吗 可以返回原值,不受影响吗

这用于必须检查其值并对其进行验证或规范化的方法。

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;
}