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 次浏览

开启你的 职业生涯

完成该课程获得认证

开始
广告
© . All rights reserved.