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

PHPz
PHPz 转载
2023-09-11 22:37:02 393浏览

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

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

调用者可以选择将返回的变量视为由 值或引用。

调用者可以创建一个新变量,该变量本身就是对返回值的引用,称为 ref local。

在下面的示例中,即使我们修改了颜色没有任何影响 原始数组颜色

示例

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 返回 -

在下面的示例中,即使我们修改颜色,它也不会产生任何影响 原始数组颜色

示例

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

Example

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

以上就是C# 7.0 中的 Ref 局部变量和 Ref 返回值是什么?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除