C#
 Computer >> コンピューター >  >> プログラミング >> C#

C#7.0でのRefローカルとRefリターンとは何ですか?


参照戻り値を使用すると、メソッドは値ではなく変数への参照を返すことができます。

呼び出し元は、返された変数を、値または参照によって返されたかのように扱うことを選択できます。

呼び出し元は、それ自体が戻り値への参照である、reflocalと呼ばれる新しい変数を作成できます。

以下の例では、色を変更しても、元の配列の色には影響しません

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

これを達成するために、reflocalsを利用できます

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

参照が返されます

以下の例では、色を変更しても、元の配列の色には影響しません

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

  1. C#のrefパラメーターとoutパラメーターの違いは何ですか?

    参照パラメータ 参照パラメータは、変数のメモリ位置への参照です。値パラメーターとは異なり、参照によってパラメーターを渡す場合、これらのパラメーターの新しい保管場所は作成されません。 refキーワードを使用して、参照パラメーターを宣言できます。以下は例です- 例 using System; namespace CalculatorApplication {    class NumberManipulator {       public void swap(ref int x, ref int y) {     &nb

  2. C#の左シフトおよび右シフト演算子(>>および<<)とは何ですか?

    ビット単位の左シフト演算子 左のオペランドの値は、右のオペランドで指定されたビット数だけ左に移動します。 ビット単位の右シフト演算子 左のオペランドの値は、右のオペランドで指定されたビット数だけ右に移動します。 以下は、ビット単位の左シフト演算子と右シフト演算子の操作方法を示す例です- 例 using System; namespace Demo {    class Program {       static void Main(string[] args) {         &nbs