为什么要使用 params 关键字? [英] Why use the params keyword?
本文介绍了为什么要使用 params 关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道这是一个基本问题,但我找不到答案.
I know this is a basic question, but I couldn't find an answer.
为什么要使用它?如果你编写了一个函数或一个使用它的方法,当你删除它时,代码仍然可以完美地工作,100% 没有它.例如:
Why use it? if you write a function or a method that's using it, when you remove it the code will still work perfectly, 100% as without it. E.g:
带参数:
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;
}
推荐答案
使用 params
你可以像这样调用你的方法:
With params
you can call your method like this:
addTwoEach(1, 2, 3, 4, 5);
没有params
,你就做不到.
此外,您可以使用数组作为参数调用该方法在两种情况下:
Additionally, you can call the method with an array as a parameter in both cases:
addTwoEach(new int[] { 1, 2, 3, 4, 5 });
也就是说,params
允许你在调用方法时使用快捷方式.
That is, params
allows you to use a shortcut when calling the method.
不相关,你可以大大缩短你的方法:
Unrelated, you can drastically shorten your method:
public static int addTwoEach(params int[] args)
{
return args.Sum() + 2 * args.Length;
}
这篇关于为什么要使用 params 关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文