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. }

当上面的代码被编译和执行时,它会产生下列结果:
在方法调用之前,a 的值: 100
在方法调用之后,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. }


/

当上面的代码被编译和执行时,它会产生下列结果(取决于用户输入):
请输入第一个值:
7
请输入第二个值:
8
在方法调用之后,a 的值: 7
在方法调用之后,b 的值: 8

out参数:返回值多个,不限类型
注意事项:

  • 调用方法之前,对out参数传递的变量只需声明,可以赋值也可以不赋值,赋值也会在方法中被覆盖掉
  • 使用out参数传递变量时,必须在方法内为其赋值,否则return的返回值没有意义
  • 方法的参数使用out修饰时,调用该方法时也要加上out关键字
  • 使用out修饰的变量不需要return