C# 7.0 中的 Ref 局部变量和 Ref 返回值是什么?

csharpserver side programmingprogramming更新于 2025/10/1 18:52:17

引用返回值允许方法返回对变量的引用,而不是值。

然后,调用者可以选择将返回的变量视为按值返回还是按引用返回。

调用者可以创建一个新变量,该变量本身是对返回值的引用,称为 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 locals

示例

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

输出

blue green yellow orange pink

示例

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

相关文章