ref和out的用法

来源:互联网 发布:js中的事件委托 编辑:程序博客网 时间:2024/05/29 13:59
 

总的来说:

通常我们向方法中传递的是值.方法获得的是这些值的一个拷贝,然后使用这些拷贝,当方法运行完毕后,这些拷贝将被丢弃,而原来的值不将受到影响.此外我们还有其他向方法传递

参数的形式,引用(ref)和输出(out).

    有时,我们需要改变原来变量中的值,这时,我们可以向方法传递变量的引用,而不是变量的值.引用是一个变量,他可以访问原来变量的值,修改引用将修改原来变量的值.变量的值存

储在内存中,可以创建一个引用,他指向变量在内存中的位置.当引用被修改时,修改的是内存中的值,因此变量的值可以将被修改.当我们调用一个含有引用参数的方法时,方法中的参

数将指向被传递给方法的相应变量,因此,我们会明白,为什么当修改参数变量的修改也将导致原来变量的值.

在次首先先说ref

方法参数上的 ref 方法参数关键字使方法引用传递到方法的同一个变量。当控制传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。

若要使用 ref 参数,必须将参数作为 ref 参数显式传递到方法。ref 参数的值被传递到 ref 参数。

传递到 ref 参数的参数必须最先初始化。将此方法与 out 参数相比,后者的参数在传递到 out 参数之前不必显式初始化。

属性不是变量,不能作为 ref 参数传递。

如果两种方法的声明仅在它们对 ref 的使用方面不同,则将出现重载。但是,无法定义仅在 ref 和 out 方面不同的重载。例如,以下重载声明是有效的:

class MyClass {   public void MyMethod(int i) {i = 10;}   public void MyMethod(ref int i) {i = 10;}}

但以下重载声明是无效的:

class MyClass {   public void MyMethod(out int i) {i = 10;}   public void MyMethod(ref int i) {i = 10;}}

示例:

REF

using System;public class MyClass {   public static void TestRef(ref char i)    {      // The value of i will be changed in the calling method      i = 'b';   }   public static void TestNoRef(char i)    {      // The value of i will be unchanged in the calling method      i = 'c';   }   // This method passes a variable as a ref parameter; the value of the    // variable is changed after control passes back to this method.   // The same variable is passed as a value parameter; the value of the   // variable is unchanged after control is passed back to this method.   public static void Main()    {         char i = 'a'; // variable must be initialized(out跟ref的区别)       TestRef(ref i); // the arg must be passed as ref       Console.WriteLine(i);       TestNoRef(i);       Console.WriteLine(i); }}    

输出
b
b

 

out

方法参数上的 out 方法参数关键字使方法引用传递到方法的同一个变量。当控制传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。

当希望方法返回多个值时,声明 out 方法非常有用。使用 out 参数的方法仍然可以返回一个值。一个方法可以有一个以上的 out 参数。

若要使用 out 参数,必须将参数作为 out 参数显式传递到方法。out 参数的值不会传递到 out 参数。

不必初始化作为 out 参数传递的变量。然而,必须在方法返回之前为 out 参数赋值。

属性不是变量,不能作为 out 参数传递。

实例:

class OutReturnExample{    static void Method(out int i, out string s1, out string s2)    {        i = 44;        s1 = "I've been returned";        s2 = null;    }    static void Main()    {        int value;         string str1, str2;//(out跟ref的区别)         Method(out value, out str1, out str2);        // value is now 44        // str1 is now "I've been returned"        // str2 is (still) null;    }}

注意红色字体