params关键字、ref、out引用传递
1.params 关键字
params关键字可以指定在参数数目可变处采用参数的方法参数。在方法申明中的params关键字之后不允许任何其他参数(这说明在params关键字之前是可以有其他参数的,除了params关键字,这个很好理解,而且呢在类型和个数方面是不受限制的),并且在方法声明中只允许一个params关键字。
实例:
using System;
namespace paramsTest
{
class Program
{
static void Main(string[] args)
{
string[] s = new string[3] { "s1", "s2", "s3" };
ParamsMethod(s);
Console.WriteLine();
ParamsMethod("p1", "p2", "p3");
Console.WriteLine();
ParamsMethod(1, 1.2, "anyone");
Console.WriteLine();
ParamsMethod(1, "jack", "chen");
Console.ReadLine();
}
public static void ParamsMethod(params object[] list)
{
for (int i = 0; i < list.Length; i++)
{
Console.WriteLine(list[i]);
}
}
public static void ParamsMethod(int id, params object[] list)
{
Console.WriteLine(id);
for (int i = 0; i < list.Length; i++)
{
Console.WriteLine(list[i]);
}
}
}
}
运行结果:
2.ref 关键字
ref关键字使参数按引用传递。其效果是,当控制权传递会调用方法之,在方法中对参数所做的任何更改都将反映在该变量中。若要使用ref参数,则方法定义和调用方法都必须显示使用ref关键字。
- 若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref 关键字。
- 传递到 ref 参数的参数必须最先初始化。这与 out 不同,out 的参数在传递之前不需要显式初始化。
- 属性不是变量,因此不能作为 ref 参数传递。
- 尽管 ref 和 out 在运行时的处理方式不同,但它们在编译时的处理方式是相同的。因此,如果一个方法采用 ref 参数,而另一个方法采用 out 参数,则无法重载这两个方法。例如,从编译的角度来看,以下代码中的两个方法是完全相同的。如果尝试这么做,将导致不能编译该代码。
- 如果一个方法采用 ref 或 out 参数,而另一个方法不采用这两类参数,则可以进行重载。
实例:
using System;
namespace refTest
{
class Program
{
static void Main(string[] args)
{
int i = 50;
Console.WriteLine("调用方法前的值i={0}", i);
RefMethod(ref i);
Console.WriteLine("调用方法后的值i={0}", i);
}
public static void RefMethod(ref int i)
{
i += 100;
Console.WriteLine("i={0}", i);
}
}
}运行结果:
3.out关键字
out关键字会导致参数通过引用传递。这与ref关键字类似,不同之处在于ref要求变量必须在传递之前进行初始化。若要使用out参数,方法定义和调用方法都必须显示使用out关键字。
尽管作为out参数传递的变量不需要在传递之前进行初始化,带需要调用方法一边在方法返回之前赋值。
例如:
using System;
namespace outTest
{
class Program
{
static void Main(string[] args)
{
int i;
Console.WriteLine("方法调用之后");
OutMethod(out i);
}
public static void OutMethod(out int i)
{
i = 50;
Console.WriteLine("i={0}", i);
}
}
}
运行结果:
小节ref和out关键字在运行时的处理方法不同,但在编译时的处理方式相同。因此,如果一个方法采用ref参数,而另一个方法采用out参数,则无法重载这两个方法。