C# - 通过引用传递参数
引用参数是对变量内存位置的引用。与值参数不同,通过引用传递参数时不会为这些参数创建新的存储位置。引用参数代表与传递给方法的实际参数相同的内存位置。
您可以使用 ref 关键字声明引用参数。以下示例演示了这一点 -
using System; namespace CalculatorApplication { class NumberManipulator { public void swap(ref int x, ref int y) { int temp; temp = x; /* 保存 x 的值 */ x = y; /* 将 y 放入 x */ y = temp; /* 将 temp 放入 y */ } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); /* 局部变量定义 */ int a = 100; int b = 200; Console.WriteLine("交换前,a 的值:{0}", a); Console.WriteLine("交换前,b 的值:{0}", b); /* 调用函数来交换值 */ n.swap(ref a, ref b); Console.WriteLine("交换后,a 的值:{0}", a); Console.WriteLine("交换后,b 的值:{0}", b); Console.ReadLine(); } } }
当编译并执行上述代码时,它会产生以下结果 -
交换前,a 的值:100 交换前,b 的值:200 交换后,a 的值:200 交换后,b 的值:100
它表明 swap 函数内部的值已发生变化,并且此变化反映在 Main 函数中。