为什么要在C#中ref和out? [英] Why ref and out in C#?

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

问题描述

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

While using keyword ref, calling code needs to initialize passed arguments, but with keyword out we need not do so.


  • 为什么我们不使用 退出 无处不在?

  • 两者有什么?

  • 请给出例子在其中,我们需要使用情况的 REF 并不能使用 退出
  • Why don't we use out everywhere?
  • What is exact difference between the two?
  • Please give example of a situation in which we need to use ref and can't use out?

推荐答案

答案在此给出的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.

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

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