c# - 为什么在 C# 中引用和输出?

标签 c#

当使用关键字ref时,调用代码需要初始化传递的参数,但是使用关键字out我们需要不要这样做。

  • 为什么我们不到处使用 out
  • 两者的确切区别是什么?
  • 请举例说明我们需要使用 ref 而不能使用 out 的情况?

最佳答案

这个MSDN article中给出了答案.来自那个帖子:

The two parameter passing modes addressed by out and ref are subtly different, however they are both very common. The subtle difference between these modes leads to some very common programming errors. These include:

  1. not assigning a value to an out parameter in all control flow paths
  2. not assigning a value to variable which is used as a ref parameter

Because 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 and out parameter passing modes was that allowing the compiler to detect these common coding errors was worth the additional complexity of having both ref and out parameter passing modes in the language.

关于c# - 为什么在 C# 中引用和输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1317162/

相关文章:

c# - 带空值的 LINQ Max()

c# - Linq to Object 的日期时间周期

c# - 确定在 .NET 中单击了哪个鼠标(多个鼠标设备)

c# - NancyFX 将日期时间反序列化为本地类型

c# - 您可以让扩展器覆盖 WPF 中的其他可视化树元素吗?

c# - 急切的 Include 函数调用内存中的数据吗?

c# - 进行拆分并将结果转换为整数的最佳方法

c# - 从 C# 到 F# 的回调

c# - 为什么 Azure 表存储操作会默默失败?

c# - CaSTLe.Windsor 使用 Dapper 实例化错误版本的 SqlConnection