最近用到了ref和out关键字,对于其概念有些遗忘,就又参考MSDN的资料学习了一下,下面是我参考MSDN整理出来的两者的简单介绍及比较: ref out 的比较:

refout关键字都是使参数通过引用来传递的,不同的是ref 要求变量必须在传递之前进行初始化,而out 的参数在传递之前不需要显式初始化。

在使用refout参数,方法定义和调用方法都必须显式使用refout关键字,如:

1out):

 


  
  1. class OutExample  
  2. {  
  3.     static void Method(out int i)  
  4.     {  
  5.         i = 44;  
  6.     }  
  7.     static void Main()  
  8.     {  
  9.         int value;  
  10.         Method(out value);  
  11.         // value is now 44  
  12.     }  
  13. }  

2ref):


  
  1. class RefExample  
  2.  {  
  3.      static void Method(ref int i)  
  4.      {  
  5.          i = 44;  
  6.      }  
  7.  
  8.     static void Main()  
  9.      {  
  10.          int val = 0;  
  11.          Method(ref val);  
  12.          // val is now 44  
  13.      }  
  14.  }  
  15.  

尽管 ref  out 在运行时的处理方式不同,但它们在编译时的处理方式是相同的。因此,如果一个方法采用 ref 参数,而另一个方法采用 out 参数,则无法重载这两个方法。例如,从编译的角度来看,以下代码中的两个方法是完全相同的,因此将不会编译以下代码:

 


  
  1. class CS0663_Example   
  2.  
  3. {  
  4.  
  5.     // compiler error CS0663: "cannot define overloaded   
  6.  
  7.     // methods that differ only on ref and out"  
  8.  
  9.     public void SampleMethod(ref int i) {  }  
  10.  
  11.     public void SampleMethod(out int i) {  }  
  12.  
  13. }  
  14.  

但是,如果一个方法采用 ref  out 参数,而另一个方法不采用这两类参数,则可以进行重载,如下所示:


  
  1. class RefOutOverloadExample  
  2. {  
  3.     public void SampleMethod(int i) {  }  
  4.     public void SampleMethod(ref int i) {  }  

 

示例:

1out

当希望方法返回多个值时,声明 out 方法很有用。使用 out 参数的方法仍然可以将变量用作返回类型,但它还可以将一个或多个对象作为 out 参数返回给调用方法。此示例使用 out 在一个方法调用中返回三个变量。请注意,第三个参数所赋的值为 Null。这样便允许方法有选择地返回值。

 


  
  1. class OutReturnExample  
  2. {  
  3.     static void Method(out int i, out string s1, out string s2)  
  4.     {  
  5.         i = 44;  
  6.         s1 = "I've been returned";  
  7.         s2 = null;  
  8.     }  
  9.     static void Main()  
  10.     {  
  11.         int value;  
  12.         string str1, str2;  
  13.         Method(out value, out str1, out str2);  
  14.         // value is now 44  
  15.         // str1 is now "I've been returned"  
  16.         // str2 is (still) null;  
  17.     }  
  18. }  

2ref

按引用传递值类型是有用的,但是 ref 对于传递引用类型也是很有用的。这允许被调用的方法修改该引用所引用的对象,因为引用本身是按引用来传递的。下面的示例显示出当引用类型作为 ref 参数传递时,可以更改对象本身。


  
  1. class RefRefExample  
  2. {  
  3.     static void Method(ref string s)  
  4.     {  
  5.         s = "changed";  
  6.     }  
  7.  
  8.     static void Main()  
  9.     {  
  10.         string str = "original";  
  11.         Method(ref str);  
  12.         // str is now "changed"  
  13.     }  
  14. }  
  15.