C# - 通过输出传递参数
return 语句只能用于从函数返回一个值。但是,使用输出参数,您可以从函数返回两个值。输出参数类似于引用参数,不同之处在于它们将数据传输出方法而不是传入方法。
以下示例对此进行了说明 -
using System;
namespace CalculatorApplication {
class NumberManipulator {
public void getValue(out int x ) {
int temp = 5;
x = temp;
}
static void Main(string[] args) {
NumberManipulator n = new NumberManipulator();
/* 局部变量定义 */
int a = 100;
Console.WriteLine("Before method call, value of a : {0}", a);
/* 调用函数获取值 */
n.getValue(out a);
Console.WriteLine("After method call, value of a : {0}", a);
Console.ReadLine();
}
}
}
当编译并执行上述代码时,它会产生以下结果 -
Before method call, value of a : 100 After method call, value of a : 5
输出参数的变量无需赋值。当你需要通过参数从方法返回值,而无需为参数赋初始值时,输出参数尤其有用。请阅读以下示例以理解这一点 -
using System;
namespace CalculatorApplication {
class NumberManipulator {
public void getValues(out int x, out int y ) {
Console.WriteLine("Enter the first value: ");
x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the second value: ");
y = Convert.ToInt32(Console.ReadLine());
}
static void Main(string[] args) {
NumberManipulator n = new NumberManipulator();
/* 局部变量定义 */
int a , b;
/* 调用函数来获取值 */
n.getValues(out a, out b);
Console.WriteLine("After method call, value of a : {0}", a);
Console.WriteLine("After method call, value of b : {0}", b);
Console.ReadLine();
}
}
}
当编译并执行上述代码时,它会产生以下结果 -
Enter the first value: 7 Enter the second value: 8 After method call, value of a : 7 After method call, value of b : 8

csharp_methods.html