C# .NET 中 ref 和 out 参数的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/135234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between ref and out parameters in .NET
提问by ashwnacharya
What is the difference between ref
and out
parameters in .NET? What are the situations where one can be more useful than the other? What would be a code snippet where one can be used and another can't?
.NET 中的ref
和out
参数有什么区别?在哪些情况下,一种比另一种更有用?一个可以使用而另一个不能使用的代码片段是什么?
采纳答案by Khoth
They're pretty much the same - the only difference is that a variable you pass as an out
parameter doesn't need to be initialized but passing it as a ref
parameter it has to be set to something.
它们几乎相同 - 唯一的区别是您作为out
参数传递的变量不需要初始化,但作为ref
参数传递它必须设置为某些东西。
int x;
Foo(out x); // OK
int y;
Foo(ref y); // Error: y should be initialized before calling the method
Ref
parameters are for data that might be modified, out
parameters are for data that's an additional output for the function (eg int.TryParse
) that are already using the return value for something.
Ref
参数用于可能被修改out
的数据,参数用于作为函数(例如int.TryParse
)的附加输出的数据,这些数据已经将返回值用于某事。
回答by Joel Coehoorn
ref will probably choke on null since it presumably expects to be modifying an existing object. out expects null, since it's returning a new object.
ref 可能会因 null 而窒息,因为它可能希望修改现有对象。out 期望 null,因为它返回一个新对象。
回答by Patrick
Ref parameters aren't required to be set in the function, whereas out parameters must be bound to a value before exiting the function. Variables passed as out may also be passed to a function without being initialized.
Ref 参数不需要在函数中设置,而 out 参数必须在退出函数之前绑定到一个值。作为 out 传递的变量也可以在未初始化的情况下传递给函数。
回答by bdukes
out
parameters are initialized by the method called, ref
parameters are initialized before calling the method. Therefore, out
parameters are used when you just need to get a secondary return value, ref
parameters are used to get a value andpotentially return a change to that value (secondarily to the main return value).
out
参数由ref
被调用的方法初始化,参数在调用方法之前被初始化。因此,out
当您只需要获取辅助返回值时ref
使用参数,参数用于获取值并可能返回对该值的更改(次要返回到主返回值)。
回答by Derek Park
Why does C# have both 'ref' and 'out'?
The caller of a method which takes an out parameter is not required to assign to the variable passed as the out parameter prior to the call; however, the callee is required to assign to the out parameter before returning.
带 out 参数的方法的调用者不需要在调用之前分配给作为 out 参数传递的变量;但是,被调用者需要在返回之前分配给 out 参数。
In contrast ref parameters are considered initially assigned by the caller. As such, the callee is not required to assign to the ref parameter before use. Ref parameters are passed both into and out of a method.
相反, ref 参数被认为是由调用者最初分配的。因此,被调用者不需要在使用前分配给 ref 参数。Ref 参数传入和传出方法。
So, out
means out, while ref
is for in and out.
所以,out
意思是out,whileref
是进进出出。
These correspond closely to the [out]
and [in,out]
parameters of COM interfaces, the advantages of out
parameters being that callers need not pass a pre-allocated object in cases where it is not needed by the method being called - this avoids both the cost of allocation, and any cost that might be associated with marshaling (more likely with COM, but not uncommon in .NET).
这些与COM 接口的[out]
和[in,out]
参数紧密对应,参数的优点out
是调用者不需要在被调用的方法不需要的情况下传递预先分配的对象 - 这既避免了分配成本,也避免了任何成本这可能与封送有关(更可能与 COM 有关,但在 .NET 中并不少见)。
回答by BlackWasp
The ref keyword is used to pass values by reference. (This does not preclude the passed values being value-types or reference types). Output parameters specified with the out keyword are for returning values from a method.
ref 关键字用于通过引用传递值。(这并不排除传递的值是值类型或引用类型)。使用 out 关键字指定的输出参数用于从方法返回值。
One key difference in the code is that you must set the value of an output parameter within the method. This is not the case for ref parameters.
代码中的一个主要区别是您必须在方法中设置输出参数的值。这不是 ref 参数的情况。
For more details look at http://www.blackwasp.co.uk/CSharpMethodParameters.aspx
有关更多详细信息,请查看http://www.blackwasp.co.uk/CSharpMethodParameters.aspx
回答by casademora
This The out and ref Paramerter in C#has some good examples.
这个C# 中的 out 和 ref 参数有一些很好的例子。
The basic difference outlined is that out
parameters don't need to be initialized when passed in, while ref parameters do.
概述的基本区别是out
参数在传入时不需要初始化,而 ref 参数则需要。
回答by Jacob Proffitt
out and ref are exactly the same with the exception that out variables don't have to be initialized before sending it into the abyss. I'm not that smart, I cribbed that from the MSDN library :).
out 和 ref 完全相同,只是 out 变量在将其发送到深渊之前不必进行初始化。我没那么聪明,我是从 MSDN 库中抄袭的 :)。
To be more explicit about their use, however, the meaning of the modifier is that if you change the reference of that variable in your code, out and ref will cause your calling variable to change reference as well. In the code below, the ceo variable will be a reference to the newGuy once it returns from the call to doStuff. If it weren't for ref (or out) the reference wouldn't be changed.
然而,为了更明确地说明它们的使用,修饰符的含义是,如果您在代码中更改该变量的引用,out 和 ref 也会导致您的调用变量也更改引用。在下面的代码中,一旦从 doStuff 调用返回,ceo 变量将成为对 newGuy 的引用。如果不是 ref (或 out),则参考不会更改。
private void newEmployee()
{
Person ceo = Person.FindCEO();
doStuff(ref ceo);
}
private void doStuff(ref Person employee)
{
Person newGuy = new Person();
employee = newGuy;
}
回答by Euro Micelli
ref
and out
both allow the called method to modify a parameter. The difference between them is what happens beforeyou make the call.
ref
并且out
都允许被调用的方法修改参数。它们之间的区别在于您拨打电话之前会发生什么。
ref
means that the parameter has a value on it beforegoing into the function. The called function can read and or change the value any time. The parameter goes in, then comes outout
means that the parameter has no official value before going into the function. The called function must initialize it. The parameter only goes out
ref
意味着参数在进入函数之前有一个值。被调用的函数可以随时读取和/或更改该值。参数进去,然后出来out
意味着参数在进入函数之前没有官方值。被调用的函数必须对其进行初始化。参数只出去
Here's my favorite way to look at it: ref
is to pass variables by reference. out
is to declare a secondary return valuefor the function. It's like if you could write this:
这是我最喜欢的看待它的方式:ref
通过引用传递变量。out
是为函数声明一个辅助返回值。就像你可以这样写:
// This is not C#
public (bool, string) GetWebThing(string name, ref Buffer paramBuffer);
// This is C#
public bool GetWebThing(string name, ref Buffer paramBuffer, out string actualUrl);
Here's a more detailed list of the effects of each alternative:
以下是每个替代方案效果的更详细列表:
Before calling the method:
在调用方法之前:
ref
: The caller must set the value of the parameter before passing it to the called method.
ref
: 调用者必须在将参数传递给被调用方法之前设置参数的值。
out
: The caller method is not required to set the value of the argument before calling the method. Most likely, you shouldn't. In fact, any current value is discarded.
out
: 调用方方法不需要在调用方法之前设置参数的值。很可能,你不应该。事实上,任何当前值都被丢弃。
During the call:
通话过程中:
ref
: The called method can read the argument at any time.
ref
: 被调用的方法可以随时读取参数。
out
: The called method must initialize the parameter before reading it.
out
: 被调用的方法必须在读取参数之前对其进行初始化。
Remoted calls:
远程调用:
ref
: The current value is marshalled to the remote call. Extra performance cost.
ref
:当前值被编组到远程调用。额外的性能成本。
out
: Nothing is passed to the remote call. Faster.
out
: 没有传递给远程调用。快点。
Technically speaking, you could use always ref
in place of out
, but out
allows you to be more precise about the meaning of the argument, and sometimes it can be a lot more efficient.
从技术上讲,您可以使用 alwaysref
代替out
,但out
可以让您更精确地了解参数的含义,有时它会更有效率。
回答by Euro Micelli
Example for OUT : Variable gets value initialized after going into the method. Later the same value is returned to the main method.
OUT 示例:变量在进入方法后获取初始化值。稍后将相同的值返回给 main 方法。
namespace outreftry
{
class outref
{
static void Main(string[] args)
{
yyy a = new yyy(); ;
// u can try giving int i=100 but is useless as that value is not passed into
// the method. Only variable goes into the method and gets changed its
// value and comes out.
int i;
a.abc(out i);
System.Console.WriteLine(i);
}
}
class yyy
{
public void abc(out int i)
{
i = 10;
}
}
}
Output:
10
输出:
10
===============================================
================================================
Example for Ref : Variable should be initialized before going into the method. Later same value or modified value will be returned to the main method.
Ref 示例:变量应在进入方法之前进行初始化。稍后相同的值或修改后的值将返回到主方法。
namespace outreftry
{
class outref
{
static void Main(string[] args)
{
yyy a = new yyy(); ;
int i = 0;
a.abc(ref i);
System.Console.WriteLine(i);
}
}
class yyy
{
public void abc(ref int i)
{
System.Console.WriteLine(i);
i = 10;
}
}
}
Output:
0 10
输出:
0 10
=================================
==================================
Hope its clear now.
希望现在清楚了。