- 在参数数目可变时采用方法参数params。
- params关键字之后不允许任何其他参数,并且在方法声明中只允许一个params关键字。
- params不允许与ref\out组合使用。
- params在你不知道参数数量时显得很有用,虽然也可以使用List等集合代替,但是params显得更直观。
- params只能用于一维数组,不能用于多维数组和诸如ArrayList、List<T>等类似于数组的集合类型。
- 因为是可变长,所以长度可以为0,也就是省略。
- 可变参数和不变参数可以同时存在。
- 若实参是数组则按引用传递,若实参是表达式则按值传递。
参考资料:
https://blog.youkuaiyun.com/dalmeeme/article/details/7193487
以下是本人调试的代码:
using System;
namespace 方法参数params
{
class Program
{
static void Main(string[] args)
{
UseParams(1, 2, 3);//可以这样调用
UseParams(new int[] { 110, 119, 120 });//也可以这样调用
UseParams();//还可以这样调用
UseParams(null);//还可以这样调用
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);
//UseParams5(1,2);参数列表中没有params,就不能这样调用了
UseParams6("chenwei", 1, 1, 1, 1, 1);//不变参数和可变参数可以同时存在
UseParams7(1, 2, 3);
int[] arr = new int[] { 4, 5, 6 };
UseParams7(arr);//若实参是数组,则按引用传递
Console.ReadLine();
}
public static void UseParams(params int[] list)
{
if (list == null)
{
Console.WriteLine("null");
return;
}
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();
}
//params必须是最后一个参数
//public static void UseParams3(params int[] list, string str)
//{
// //
//}
//params不允许与ref\out组合使用
//public static void UseParams4(params ref int[] list)
//{
// //
//}
public static void UseParams5(int[] list)
{
Console.WriteLine("这是5");
}
public static void UseParams6(string name, params int[] arr)
{
Console.WriteLine(name);
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
Console.WriteLine();
}
public static void UseParams7(params int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
arr[i] = 0;
}
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
Console.WriteLine();
}
}
}