参数数组用 params 修饰符声明。一个给定的方法只能有一个参数数组,而且它必须始终是最后一个指定的参数。参数数组的类型总是一维数组类型。调用方可以传递一个属同一类型的数组变量,或任意多个与该数组的元素属同一类型的自变量。例如,示例
using System;
class Test 
{
static void F(params int[] args) {
Console.WriteLine("# of arguments: {0}", args.Length);
for (int i = 0; i < args.Length; i++)
Console.WriteLine("\targs[{0}] = {1}", i, args[i]);
}
static void Main() {
F();
F(1);
F(1, 2);
F(1, 2, 3);
F(new int[] {1, 2, 3, 4});
}
}
显示了带数目可变的 int 参数的方法 F,以及对此方法的若干个调用。输出为:
# of arguments: 0
# of arguments: 1
args[0] = 1
# of arguments: 2
args[0] = 1
args[1] = 2
# of arguments: 3
args[0] = 1
args[1] = 2
args[2] = 3
# of arguments: 4
args[0] = 1
args[1] = 2
args[2] = 3
args[3] = 4
此介绍中出现的大部分示例使用 Console 类的 WriteLine 方法。此方法的参数替换行为(如下面的示例所示)
int a = 1, b = 2;
Console.WriteLine("a = {0}, b = {1}", a, b);
是使用参数数组完成的。为适应常见的各种需要,WriteLine 方法有若干个重载的方法供选用,这些方法中,有些需传递固定个数的参数,有些使用了参数数组。
namespace System
{
public class Console
{
public static void WriteLine(string s) {...}
public static void WriteLine(string s, object a) {...}
public static void WriteLine(string s, object a, object b) {...}
...
public static void WriteLine(string s, params object[] args) {...}
}
}