如何在 C# 方法中通过引用传递参数?
csharpprogrammingserver side programming
引用参数是对变量内存位置的引用。通过引用传递参数时,与值参数不同,不会为这些参数创建新的存储位置。
引用参数表示与提供给方法的实际参数相同的内存位置。
以下是显示如何通过引用传递参数的示例。使用 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