一、params 是C#开发语言中关键字, params主要的用处是在给函数传参数的时候用,就是当函数的参数不固定的时候。 关于参数数组,需掌握以下几点。
1、被加上params关键字的形参,必须是形参列表中最后一个形参,并且方法声明中只允许一个 params 关键字。
2、若形参表中含一个参数数组,则该参数数组必须位于形参列表的最后。
3、不允许将params修饰符与ref和out修饰符组合起来使用。
4、params只能用于一维数组,不能用于多维数组和诸如ArrayList、List等任何类似于数组的集合类型。
5、与参数数组对应的实参可以是同一类型的数组名,也可以是任意多个与该数组的元素属于同一类型的变量。
6、若实参是数组则按引用传递,若实参是变量或表达式则按值传递。
例如,下面代码:
public class ExercisesEight
{
public static int paramsShowMaxValue(params int[] arr)
{
int maxValue = 0;
if (arr != null && arr.Length > 0)
{
Array.Sort(arr);
maxValue = arr[arr.Length - 1];
}
return maxValue;
}
public static void paramsShowMaxValue(string str,params int[] arr)
{
{
//dosomething........
}
}
}
方法调用:
Console.WriteLine($"最大值为:{ExercisesEight.paramsShowMaxValue()}");
Console.WriteLine($"最大值为:{ExercisesEight.paramsShowMaxValue(5)}");
Console.WriteLine($"最大值为:{ExercisesEight.paramsShowMaxValue(15,2)}");
Console.WriteLine($"最大值为:{ExercisesEight.paramsShowMaxValue(5,9,6,7,20,90,100,99)}");
Console.WriteLine($"最大值为:{ExercisesEight.paramsShowMaxValue(new int[] { 6,5,2,7,10,20,60,4})}");
输出结果:
注意:用params关键字的方法,有三种调用形式:
第一种,列举出数组各元素:paramsShowMaxValue(1,2,3),这也是最常用的形式;
第二种,像没有加params关键字的数组形参那样,用数组名做实参:paramsShowMaxValue(new int[]{1,2,3})或int n=new int[]{1,2,3};paramsShowMaxValue(n);;
第三种,加params关键字的参数在调用时可以省略:paramsShowMaxValue();//返回0;这种方式有时可以少定义一个方法重载,但当明确定义了重载int paramsShowMaxValue()时,编译器会优先调用int paramsShowMaxValue(),而不是paramsShowMaxValue(params int[] arr)。而且省略params型参数,方法内部仍会new一个元素个数为0的数组,效率略查。
第四种,不省略params型参数,用null代替,效率比第三种略高,因为其内部不会new这个数组。