---------------------- Windows Phone 7手机开发、.Net培训、期待与您交流! ----------------------
params 关键字可以指定在参数数目可变处采用参数的方法参数。
such as :在控制台程序
using System;
public class MyClass
{
public static void UseParams(params int[] list) //方法一,传入一个可变int数组
{
for (int i = 0 ; i < list.Length; i++)
{
Console.WriteLine(list[i]);
}
Console.WriteLine();
}
public static void UseParams2(params object[] list) 方法二传入一个object可变数组
{
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);
}
}
输出:
1
2
3
1
a
test
10
11
12
(部分内容引用自msdn)
在需要传入多个参数的情况下
public static void UseParams2(string name,params object[] list) //需要多个参数的方法
{
this.name=name;
for (int i = 0 ; i < list.Length; i++)
{
Console.WriteLine(list[i]);
}
Console.WriteLine();
}
如果方法要求传入两个参数,那么params的可变数组只能放在后边,默认第一个传入的是string 的 name 后边传入的是这个数组,不然会导致错误