为什么要使用params关键字?我知道这是一个基本问题,但我找不到答案。为什么要用它?如果你编写一个函数或一个使用它的方法,当你删除它时代码仍然可以完美地工作,100%没有它。例如:使用params:static public int addTwoEach(params int[] args){
int sum = 0;
foreach (var item in args)
sum += item + 2;
return sum;}没有参数:static public int addTwoEach(int[] args){
int sum = 0;
foreach (var item in args)
sum += item + 2;
return sum;}
3 回答
有只小跳蛙
TA贡献1824条经验 获得超8个赞
有了params你可以打电话给你的方法是这样的:
addTwoEach(1, 2, 3, 4, 5);
没有params,你不能。
此外,在以下两种情况下,您都可以使用数组作为参数调用该方法:
addTwoEach(new int[] { 1, 2, 3, 4, 5 });也就是说,params允许您在调用方法时使用快捷方式。
不相关的,你可以大大缩短你的方法:
public static int addTwoEach(params int[] args){
return args.Sum() + 2 * args.Length;}
缥缈止盈
TA贡献2041条经验 获得超4个赞
使用params允许您调用没有参数的函数。没有params:
static public int addTwoEach(int[] args){
int sum = 0;
foreach (var item in args)
{
sum += item + 2;
}
return sum;}addtwoEach(); // throws an error比较params:
static public int addTwoEach(params int[] args){
int sum = 0;
foreach (var item in args)
{
sum += item + 2;
}
return sum;}addtwoEach(); // returns 0通常,当参数数量从0到无穷大时,您可以使用参数,并在参数数量从1到无穷大时使用数组。
- 3 回答
- 0 关注
- 726 浏览
添加回答
举报
0/150
提交
取消
