1. 程式人生 > >關於ref和out

關於ref和out

方法引數上的 ref 關鍵字使方法引用傳遞到方法的同一個變數。當控制傳遞迴呼叫方法時,在方法中對引數所做的任何更改都將反映在該變數中。若要使用 ref 引數,必須將引數作為 ref 引數顯式傳遞到方法。ref 引數的值被傳遞到 ref 引數。

傳遞到 ref 引數的引數必須最先初始化。將此方法與 out 引數相比,後者的引數在傳遞到 out 引數之前不必顯式初始化。

屬性不是變數,不能作為 ref 引數傳遞。

如果兩種方法的宣告僅在它們對 ref 的使用方面不同,則將出現過載。但是,無法定義僅在 refout 方面不同的過載。例如,以下過載宣告是有效的:

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);   }}

輸出

-1b