c#中参数关键字params、ref、out

params:指定在参数数目可变处采用参数的方法参数;它后面不允许任何其它参数,并且只允许有一个params参数。

params
// cs_params.cs
using System;
public class MyClass
{

public static void UseParams(params int[] list)
{
for (int i = 0 ; i < list.Length; i++)
{
Console.WriteLine(list[i]);
}
Console.WriteLine();
}

public static void UseParams2(params object[] list)
{
for (int i = 0 ; i < list.Length; i++)
{
Console.WriteLine(list[i]);
}
Console.WriteLine();
}

static void Main()
{
UseParams(
1, 2, 3);
UseParams2(
1, 'a', "test");

// An array of objects can also be passed, as long as
// the array type matches the method being called.
int[] myarray = new int[3] {10,11,12};
UseParams(myarray);
}
}

ref使参数按引用传递;其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中;传递到 ref 参数的参数必须最先初始化,这与 out 不同,out 的参数在传递之前不需要显式初始化。

ref
class RefExample
{
static void Method(ref int i)
{
i
= 44;
}
static void Main()
{
int val = 0;
Method(
ref val);
// val is now 44
}
}

out使参数按引用传递;其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中;传递到out参数的参数需要调用方法以便在方法返回之前赋值,这与ref不同,ref的参数在传递之前需要显式初始化。

out
class OutExample
{
static void Method(out int i)
{
i
= 44;
}
static void Main()
{
int value;
Method(
out value);
// value is now 44
}
}

posted @ 2011-03-29 10:03  [曾恩]  阅读(286)  评论(0编辑  收藏  举报