>  기사  >  백엔드 개발  >  C# 7.0의 Ref 지역 변수와 Ref 반환 값은 무엇입니까?

C# 7.0의 Ref 지역 변수와 Ref 반환 값은 무엇입니까?

PHPz
PHPz앞으로
2023-09-11 22:37:02778검색

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

참조 반환 값을 사용하면 메소드가 대신 변수에 대한 참조를 반환할 수 있습니다. 가치보다.

호출자는 반환된 변수를 다음과 같이 처리하도록 선택할 수 있습니다. 값 또는 참조.

호출자는 ref local이라는 반환 값에 대한 참조인 새 변수를 생성할 수 있습니다.

아래 예시에서는 색상을 수정해도 아무런 효과가 없습니다 원시 배열 색상

Example

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

Output

blue green yellow orange pink

이를 달성하기 위해 ref locals를 사용할 수 있습니다.

Example

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

Output

blue green yellow Magenta pink

Ref는 -

아래 예에서는 색상을 수정하더라도 역시 효과가 없다 원래 배열 색상

Example

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

output

파란색 녹색 노란색 주황색 분홍색

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

output

blue green yellow Magenta pink

위 내용은 C# 7.0의 Ref 지역 변수와 Ref 반환 값은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제