3, params
params关键字可以指定在参数数目可变处采用参数的方法参数。
- 在方法声明中的 params 关键字之后不允许任何其他参数,并且在方法声明中只允许一个 params 关键字。
字面意思比较难懂,所以看示例很有用。
using System;
class App
{
public static voidUseParams(params object[] list)
{
for (int i = 0; i< list.Length; i++)
{
Console.WriteLine(list[i]);
}
}
static void Main()
{
// 一般做法是先构造一个对象数组,然后将此数组作为方法的参数
object[] arr = newobject[3] { 100, 'a', "keywords" };
UseParams(arr);
// 而使用了params修饰方法参数后,我们可以直接使用一组对象作为参数
// 当然这组参数需要符合调用的方法对参数的要求
UseParams(100,'a', "keywords");
Console.Read();
}
}
关键字:ref和out
- 若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref 关键字。
- 传递到 ref 参数的参数必须最先初始化。这与 out 不同,out 的参数在传递之前不需要显式初始化。
// keywords_ref.cs
using System;
class App
{
public static void UseRef(ref int i)
{
i += 100;
Console.WriteLine("i = {0}",i);
}
static void Main()
{
int i = 10;
// 查看调用方法之前的值
Console.WriteLine("Before themethod calling: i = {0}", i);
UseRef(ref i);
// 查看调用方法之后的值
Console.WriteLine("After themethod calling: i = {0}", i);
Console.Read();
}
}
/*
控制台输出:
Beforethe method calling : i = 10
i = 110
Afterthe method calling: i = 110
*/