1、params 是C#开发语言中关键字, params主要的用处是在给函数传参数的时候用,就是当函数的参数不固定的时候。 在方法声明中的 params 关键字以后不容许任何其余参数,而且在方法声明中只容许一个 params 关键字。 关于参数数组,需掌握如下几点。数组
一、若形参表中含一个参数数组,则该参数数组必须位于形参列表的最后。函数
二、不容许将params修饰符与ref和out修饰符组合起来使用。spa
三、参数数组必须是一维数组。code
四、与参数数组对应的实参能够是同一类型的数组名,也能够是任意多个与该数组的元素属于同一类型的变量。blog
五、若实参是数组则按引用传递,若实参是变量或表达式则按值传递。ci
2、示例代码开发
示例代码以返回最大值为例。string
一、方法定义:it
1 public class ExercisesEight 2 { 3 public static int paramsShowMaxValue(params int[] arr) 4 { 5 int maxValue = 0; 6 if (arr != null && arr.Length > 0) 7 { 8 Array.Sort(arr); 9 maxValue = arr[arr.Length - 1]; 10 } 11 return maxValue; 12 } 13 public static void paramsShowMaxValue(string str,params int[] arr) 14 { 15 16 { 17 //dosomething........ 18 } 19 } 20 21 22 }
二、调用方法class
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})}");
输出结果: