且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么要在C#中ref和out?

更新时间:2022-06-20 21:43:52

答案在此给出的MSDN文章。从这个职位:

The answer is given in this MSDN article. From that post:

解决这两个参数传递模式
OUT
REF 是微妙
不同,但它们都是一些常见的都非常
。 b这些模式$ B $之间的细微差别导致了一些很普通的
编程错误。这些措施包括:

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. 没有赋值给退出
    参数在所有的控制流路径

  2. 不分配值变量
    被用作一个 REF 参数

  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

由于C#语言分配
不同的赋值规则,以
这些不同的参数传递
模式,这些常见的编码错误是
。通过编译器捕获作为是
不正确的C#代码。

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.

的决定将
两者的症结 REF 退出参数传递
模式是允许编译器
,来检测这些常见的编码错误
是值得
具有两个 REF 退出参数
传递模式的额外的复杂性在语言。

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.