介绍
params 是c#的一个关键字,修饰形参,表示形参的个数可变
例子
声明
static void ParamtesDemo(string className, params string[] names)
{
Console.WriteLine($"{className}的学生有:{string.Join(",", names)}");
}
注意:
- params修饰在参数的前面且参数类型得是一维数组类型
- params修饰在参数必须在最后
- params修饰的参数默认是可以不传递的
- params参数不能用
ref或out修饰,且不能手动给默认值
调用
ParamtesDemo("小四班", "jordan", "kobe", "james", "curry");
// 如果不传递值也不会报错
// ParamtesDemo("小四班");
例子2
声明
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;
}
调用
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})}");
参考:
https://www.cnblogs.com/wucy/p/15870366.html
https://www.cnblogs.com/maowp/p/8134342.html