使用REF和放大器; OUT关键字与参考和放大器传递;按值在C#中传递 [英] Using REF & OUT keywords with Passing by Reference & Passing by Value in C#

查看:224
本文介绍了使用REF和放大器; OUT关键字与参考和放大器传递;按值在C#中传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过单元副本参数的传递。
更改该副本不改变原来的。

Passing by value means a copy of an argument is passed. Changes to that copy do not change the original.

通过引用传递装置到原始的引用传递。
改变为参考影响原来的。

Passing by reference means a reference to the original is passed. changes to the reference affect the original.

REF告诉编译器的物体在进入函数之前初始化。
REF装置的值已被设置,则该方法可因此读它并进行修改。
REF是两种方式,在国内外享有很高。

REF tells the compiler that the object is initialized before entering the function. REF means the value is already set, the method can therefore read it and modify it. REF is two ways, both in and out.

OUT告诉编译器该对象将在函数中intialized。
OUT装置的值尚未设置,因此,必须在调用返回之前设置。
OUT只有一个办法,这也不行。

OUT tells the compiler that the object will be intialized inside the function. OUT means the value is not already set, and therefore must be set before calling return. OUT is only one way, which is out.

因此,在什么情况下会通过引用结合使用ref和out关键字,以传递或按值传递?
例子有极大帮助。

So in what scenarios would you combine the use of the ref and out keywords, with passing by reference or passing by value? Examples would help tremendously.

帮助非常感谢。

推荐答案

您会绝不会 REF 退出 1的参数。他们都指按引用传递。

You would never combine ref and out on 1 parameter. They both mean 'pass by reference'.

您当然可以结合参考参数和出一种方法的参数。

You can of course combine ref parameters and out parameters in one method.

之间的差异 REF 退出主要在于意图。 REF信号2路数据传输,意味着出1路。

The difference between ref and out lies mainly in intent. ref signals 2-way data transport, out means 1-way.

但是,除了意图,C#编译器跟踪明确赋值,这使得最显着的区别。它还可以防止out参数的误用(读)。

But besides intent, the C# compiler tracks definite-assignment and that makes the most noticable difference. It also prevents the misuse (reading) of an out parameter.

void SetOne(out int x) 
{
  int y = x + 1; // error, 'x' not definitely assigned.
  x = 1;         // mandatory to assign something
}

void AddTwo(ref int x)
{
    x = x + 2;  // OK, x  is known to be assigned
}

void Main()
{
    int foo, bar;

    SetOne(out foo); // OK, foo does not have to be assigned
    AddTwo(ref foo); // OK, foo assigned by SetOne
    AddTwo(ref bar); // error, bar is unassigned
}

这篇关于使用REF和放大器; OUT关键字与参考和放大器传递;按值在C#中传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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