C# 7.0 中的 Ref 區域性變數和 Ref 返回值是什麼?


引用返回值允許方法返回對變數的引用,而不是值。

然後,呼叫者可以選擇將返回變數視為透過值或引用返回。

呼叫者可以建立一個新變數,該變數本身是對返回值的引用,稱為 ref 區域性變數。

在下面的示例中,即使我們修改了顏色,也不會對原始陣列 colors 產生任何影響

示例

class Program{
   public static void Main(){
      var colors = new[] { "blue", "green", "yellow", "orange", "pink" };
      string color = colors[3];
      color = "Magenta";
      System.Console.WriteLine(String.Join(" ", colors));
      Console.ReadLine();
   }
}

輸出

blue green yellow orange pink

要實現此目的,我們可以使用 ref 區域性變數

示例

public static void Main(){
   var colors = new[] { "blue", "green", "yellow", "orange", "pink" };
   ref string color = ref colors[3];
   color = "Magenta";
   System.Console.WriteLine(String.Join(" ", colors));
   Console.ReadLine();
}

輸出

blue green yellow Magenta pink

Ref 返回

在下面的示例中,即使我們修改了顏色,也不會對原始陣列 colors 產生任何影響

示例

class Program{
   public static void Main(){
      var colors = new[] { "blue", "green", "yellow", "orange", "pink" };
      string color = GetColor(colors, 3);
      color = "Magenta";
      System.Console.WriteLine(String.Join(" ", colors));
      Console.ReadLine();
   }
   public static string GetColor(string[] col, int index){
      return col[index];
   }
}

輸出

藍色 綠色 黃色 橙色 粉紅色

示例

class Program{
   public static void Main(){
      var colors = new[] { "blue", "green", "yellow", "orange", "pink" };
      ref string color = ref GetColor(colors, 3);
      color = "Magenta";
      System.Console.WriteLine(String.Join(" ", colors));
      Console.ReadLine();
   }
   public static ref string GetColor(string[] col, int index){
      return ref col[index];
   }
}

輸出

blue green yellow Magenta pink

更新於: 19-8-2020

565 次瀏覽

開啟你的 職業生涯

完成該課程獲得認證

開始
廣告