C#提供out关键字以将参数作为out-type传递。它类似于引用类型,只是它不需要变量在传递之前进行初始化。我们必须使用out关键字将参数作为out-type传递。当我们想要一个函数返回多个值时,这很有用。
C#输出参数示例1
using System;
namespace OutParameter
{
class Program
{
// User defined function
public void Show(out int val) // Out parameter
{
int square = 5;
val = square;
val *= val; // Manipulating value
}
// Main function, execution entry point of the program
static void Main(string[] args)
{
int val = 50;
Program program = new Program(); // Creating Object
Console.WriteLine("Value before passing out variable " + val);
program.Show(out val); // Passing out argument
Console.WriteLine("Value after recieving the out variable " + val);
}
}
}
输出:
Value before passing out variable 50
Value after receiving the out variable 25
下面的示例演示函数如何返回多个值。
C#输出参数示例2
using System;
namespace OutParameter
{
class Program
{
// User defined function
public void Show(out int a, out int b) // Out parameter
{
int square = 5;
a = square;
b = square;
// Manipulating value
a *= a;
b *= b;
}
// Main function, execution entry point of the program
static void Main(string[] args)
{
int val1 = 50, val2 = 100;
Program program = new Program(); // Creating Object
Console.WriteLine("Value before passing \n val1 = " + val1+" \n val2 = "+val2);
program.Show(out val1, out val2); // Passing out argument
Console.WriteLine("Value after passing \n val1 = " + val1 + " \n val2 = " + val2);
}
}
}
输出:
Value before passing
val1 = 50
val2 = 100
Value after passing
val1 = 25
val2 = 25
评论前必须登录!
注册