按引用传递参数

引用参数是一个对变量的内存位置的引用。当按引用传递参数时,与值参数不同的是,它不会为这些参数创建一个新的存储位置。引用参数表示与提供给方法的实际参数具有相同的内存位置。和指针类似,指向地址。
在 C# 中,使用 ref 关键字声明引用参数。下面的实例演示了这点:

实例

  1. using System;
  2. namespace CalculatorApplication
  3. {
  4. class NumberManipulator
  5. {
  6. public void swap(ref int x, ref int y) //不加ref的话就是形参,改变形参不会影响到实参
  7. {
  8. int temp;
  9. temp = x; /* 保存 x 的值 */
  10. x = y; /* 把 y 赋值给 x */
  11. y = temp; /* 把 temp 赋值给 y */
  12. }
  13. static void Main(string[] args)
  14. {
  15. NumberManipulator n = new NumberManipulator();
  16. /* 局部变量定义 */
  17. int a = 100;
  18. int b = 200;
  19. Console.WriteLine("在交换之前,a 的值: {0}", a);
  20. Console.WriteLine("在交换之前,b 的值: {0}", b);
  21. /* 调用函数来交换值 */
  22. n.swap(ref a, ref b);
  23. Console.WriteLine("在交换之后,a 的值: {0}", a);
  24. Console.WriteLine("在交换之后,b 的值: {0}", b);
  25. Console.ReadLine();
  26. }
  27. }
  28. }

当上面的代码被编译和执行时,它会产生下列结果:
在交换之前,a 的值:100
在交换之前,b 的值:200
在交换之后,a 的值:200
在交换之后,b 的值:100
结果表明,swap 函数内的值改变了,且这个改变可以在 Main 函数中反映出来。