天天看點

關于ref和out

方法參數上的 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;}
}      
// cs_ref.cs
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
      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 的使用方面不同,則會發生重載。不過,無法定義僅在 ref 和 out 方面不同的重載。例如,以下重載聲明是有效的:

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

而以下重載聲明是無效的:

class MyClass 
{
   public void MyMethod(out int i) {i = 10;}
   public void MyMethod(ref int i) {i = 10;}
}      
// example:cs_out.cs 
using System;
public class MyClass 
{
   public static int TestOut(out char i) 
   {
      i = 'b';
      return -1;
   }

   public static void Main() 
   {
      char i;   // variable need not be initialized
      Console.WriteLine(TestOut(out i));
      Console.WriteLine(i);
   }
}      

輸出

-1
b