当使用关键字ref
时,调用代码需要初始化传递的参数,但是使用关键字out
我们需要不要这样做。
- 为什么我们不到处使用
out
? - 两者的确切区别是什么?
- 请举例说明我们需要使用
ref
而不能使用out
的情况?
最佳答案
这个MSDN article中给出了答案.来自那个帖子:
The two parameter passing modes addressed by
out
andref
are subtly different, however they are both very common. The subtle difference between these modes leads to some very common programming errors. These include:
- not assigning a value to an
out
parameter in all control flow paths- not assigning a value to variable which is used as a
ref
parameterBecause the C# language assigns different definite assignment rules to these different parameter passing modes, these common coding errors are caught by the compiler as being incorrect C# code.
The crux of the decision to include both
ref
andout
parameter passing modes was that allowing the compiler to detect these common coding errors was worth the additional complexity of having bothref
andout
parameter passing modes in the language.
关于c# - 为什么在 C# 中引用和输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1317162/