按引用传递参数 ref

引用参数是一个对变量的内存位置的引用。引用参数表示与提供给方法的实际参数具有相同的内存位置。
在 C# 中,使用 ref 关键字声明引用参数。下面的实例演示了这点:

  1. using System;
  2. namespace CalculatorApplication
  3. {
  4. class NumberManipulator
  5. {
  6. public void swap(ref int x, ref int y)
  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. }

当上面的代码被编译和执行时,它会产生下列结果:

  1. 在交换之前,a 的值:100
  2. 在交换之前,b 的值:200
  3. 在交换之后,a 的值:200
  4. 在交换之后,b 的值:100

按输出传递参数 out

return 语句可用于只从函数中返回一个值。但是,可以使用 输出参数 来从函数中返回两个值。输出参数会把方法输出的数据赋给自己,其他方面与引用参数相似。
下面的实例演示了这点:

  1. using System;
  2. namespace CalculatorApplication
  3. {
  4. class NumberManipulator
  5. {
  6. public void getValue(out int x )
  7. {
  8. int temp = 5;
  9. x = temp;
  10. }
  11. static void Main(string[] args)
  12. {
  13. NumberManipulator n = new NumberManipulator();
  14. /* 局部变量定义 */
  15. int a = 100;
  16. Console.WriteLine("在方法调用之前,a 的值: {0}", a);
  17. /* 调用函数来获取值 */
  18. n.getValue(out a);
  19. Console.WriteLine("在方法调用之后,a 的值: {0}", a);
  20. Console.ReadLine();
  21. }
  22. }
  23. }

当上面的代码被编译和执行时,它会产生下列结果:

  1. 在方法调用之前,a 的值: 100
  2. 在方法调用之后,a 的值: 5

提供给输出参数的变量不需要赋值。当需要从一个参数没有指定初始值的方法中返回值时,输出参数特别有用。请看下面的实例,来理解这一点:

  1. using System;
  2. namespace CalculatorApplication
  3. {
  4. class NumberManipulator
  5. {
  6. public void getValues(out int x, out int y )
  7. {
  8. Console.WriteLine("请输入第一个值: ");
  9. x = Convert.ToInt32(Console.ReadLine());
  10. Console.WriteLine("请输入第二个值: ");
  11. y = Convert.ToInt32(Console.ReadLine());
  12. }
  13. static void Main(string[] args)
  14. {
  15. NumberManipulator n = new NumberManipulator();
  16. /* 局部变量定义 */
  17. int a , b;
  18. /* 调用函数来获取值 */
  19. n.getValues(out a, out b);
  20. Console.WriteLine("在方法调用之后,a 的值: {0}", a);
  21. Console.WriteLine("在方法调用之后,b 的值: {0}", b);
  22. Console.ReadLine();
  23. }
  24. }
  25. }

当上面的代码被编译和执行时,它会产生下列结果(取决于用户输入):

  1. 请输入第一个值:
  2. 7
  3. 请输入第二个值:
  4. 8
  5. 在方法调用之后,a 的值: 7
  6. 在方法调用之后,b 的值: 8