.NET中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参数由调用的方法初始化,ref参数在调用方法之前初始化。因此,当您只需要获得第二个返回值时,使用out参数,ref参数用于获取一个值并可能返回对该值的更改(次于主返回值)。

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

ref关键字用于通过引用传递值。(这并不排除传递的值是值类型或引用类型)。用out关键字指定的输出参数用于从方法返回值。

代码中的一个关键区别是必须在方法中设置输出参数的值。对于ref参数则不是这样。

欲了解更多细节,请访问http://www.blackwasp.co.uk/CSharpMethodParameters.aspx

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

Out指定参数是输出参数,也就是说,在方法显式设置它之前,它没有值。

Ref指定该值是一个具有值的引用,并且您可以在方法中更改其值。