如何在C#中分配对变量的引用

要将引用分配给变量,请使用ref关键字。引用参数是对变量的存储位置的参考。当您通过引用传递参数时,与值参数不同,不会为这些参数创建新的存储位置。使用ref关键字声明引用参数。

让我们看一个例子-

在这里,我们使用ref关键字交换两个值-

示例

using System;

namespace Demo {
   class Program {
      public void swap(ref int x, ref int y) {
         int temp;

         temp = x; /* save the value of x */
         x = y; /* put y into x */
         y = temp; /* put temp into y */
      }

      static void Main(string[] args) {
         Program p = new Program();

         /* local variable definition */
         int a = 99;
         int b = 110;

         Console.WriteLine("Before swap, value of a : {0}", a);
         Console.WriteLine("Before swap, value of b : {0}", b);

         /* calling a function to swap the values */
         p.swap(ref a, ref b);

         Console.WriteLine("After swap, value of a : {0}", a);
         Console.WriteLine("After swap, value of b : {0}", b);

         Console.ReadLine();
      }
   }
}

输出结果

Before swap, value of a : 99
Before swap, value of b : 110
After swap, value of a : 110
After swap, value of b : 99