C#中的out和ref参数 [英] The out and ref Parameter in C#

查看:91
本文介绍了C#中的out和ref参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它们之间有什么区别?

我们何时何地应该使用OUT和REF?

编程示例?

RealWorld示例

..

谢谢。

非常感谢积极的讨论。

what is the difference between them?
when or where we should use OUT and REF?
Programming example?
RealWorld Example
..
thank you.
Positive discussion is appreciated.

推荐答案

它们几乎相同,它们的低级实现是相同的;唯一的区别是对方法实现的语法要求。



如果参数为out,编译器会强制为参数赋值。更准确地说,如果编译器可以看到此参数未分配的情况,则会生成编译错误。这是一个强大的万无一失的功能。



ref参数强加了更宽松的规则,足以进出行为。不需要修改此参数的值。如果该值在返回时没有修改,那就没问题,价值将保持与通话前相同。



我忘了提及out变量不必初始化。我上面提到的要求允许考虑在调用和保证初始化之后初始化的变量。当然,ref参数需要初始化。感谢Monjurul。



-SA
They are almost the same and their low-level implementations are identical; the only difference is the syntax requirements to the implementation of the method.

If the argument is "out", the compiler enforces assignment of a new value to the parameter. More exactly, if a compiler can see the situation where this parameter is left unassigned, it generates a compilation error. This is a powerful fool-proof feature.

The "ref" argument impose more relaxed rules which is adequate to "in-out" behavior. Modification of the value of this parameter is not required. If the value is not modifies on return, it''s fine, the value will remain the same as before the call.

I forgot to mention that "out" variable does not have to be initialized. The requirement I mentioned above allows to consider such variable as initialized after the call and guarantee initialization. Of course "ref" parameter is required to be initialized. Credit to Monjurul.

—SA


两者非常相似 - 唯一的区别是您传递的变量 out 参数不需要初始化,并且使用out参数的方法必须设置它的东西。

Both are pretty similar - the only difference is that a variable you pass as an out parameter doesn''t need to be initialized, and the method using the out parameter has to set it to something.
int a;
Item(out a); // OK

int b;
Item(ref b); // Not Ok





参考参数适用于可能被修改的数据 out 参数用于函数的附加输出的数据(例如int.TryParse)已经使用某些东西的返回值。



欲了解更多详情,请访问以下链接:

C#中的out和ref Paramerter

C#中out和ref有什么区别?



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.

For more detail information please visit the following link:
The out and ref Paramerter in C#
What is the difference between out and ref in C#?


我搜索并遇到了这个问题 [ ^ ]问道。应该帮助你。
I searched and came across this question[^] asked a few months ago. Should help you out.


这篇关于C#中的out和ref参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆