using System;
namespace ParameterPass
{
/// <summary>
/// ParameterPassClass 的摘要说明。
/// </summary>
class ParameterPassClass
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
int a, b;
a = 10;
b = 20;
Console.WriteLine("调用传值函数前:a = {0} b = {1}", a, b);
// 传值操作,并不改变a,b的值
SwapParameter(a, b);
Console.WriteLine("调用传值函数后:a = {0} b = {1}/n", a, b);
Console.WriteLine("调用传引用函数前:a = {0} b = {1}", a, b);
// 传引用操作,在此必须明确写出ref关键字
SwapRefParameter(ref a, ref b);
Console.WriteLine("调用传引用函数后:a = {0} b = {1}/n", a, b);
int sum;
SwapOutParameter(a, b, out sum);
Console.WriteLine("使用out关键字");
Console.WriteLine("a + b = {0}/n", sum);
// 参量参数调用
SwapParams();
SwapParams(1, 2);
SwapParams(new int[] {1, 2, 3});
Console.ReadLine();
}
// 传值操作
public static void SwapParameter(int a, int b)
{
int n;
n = a;
a = b;
b = n;
}
// 值的引用,这里的参数并不另外开辟存储空间,而是引用所传递参数的地址
// 使用关键字ref,传入的值必须被初始化
public static void SwapRefParameter(ref int a, ref int b)
{
int n;
n = a;
a = b;
b = n;
}
// 使用out关键字不需要将变量初始化
public static void SwapOutParameter(int a, int b, out int sum)
{
sum = a + b;
}
// 参量参数,关键字params
public static void SwapParams(params int[] args)
{
Console.WriteLine("参数长度:{0}", args.Length);
for (int i=0; i<args.Length; i++)
Console.WriteLine("args[{0}] = {1}", i, args[i]);
}
}
}
参数传递及关键字params,ref,out的使用
最新推荐文章于 2021-10-10 10:19:30 发布