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();
/* local variable definition */
int a = 100;
Console.WriteLine("Before method call, value of a : {0}", a);
/* calling a function to get the value */
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();
/* local variable definition */
int a , b;
/* calling a function to get the values */
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:
17
Enter the second value:
19
After method call, value of a : 17
After method call, value of b : 19
上一篇:
C#方法
下一篇:
C#可空类型(nullable)