为什么要使用params关键字? [英] Why use the params keyword?

查看:198
本文介绍了为什么要使用params关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个基本问题,但我无法找到答案。

为什么要使用它?如果你写一个函数或目前正使用它的方法,当你删除它code仍然会很好地工作,100%,因为没有它。例如:

使用参数:

 静态公众诠释addTwoEach(PARAMS INT []参数)
{
    INT总和= 0;
    的foreach(在args VAR项)
        总和+ =项目+ 2;
    返回总和;
}

无PARAMS:

 静公众诠释addTwoEach(中间体[]参数)
{
    INT总和= 0;
    的foreach(在args VAR项)
       总和+ =项目+ 2;
    返回总和;
}


解决方案

随着 PARAMS 你可以调用你的方法是这样的:

  addTwoEach(1,2,3,4,5);

没有 PARAMS ,你不能。

此外,您可以调用与数组中的方法,在这两个情况下,一个参数的 的:

  addTwoEach(新INT [] {1,2,3,4,5});

这是 PARAMS ,您可以使用快捷方式调用该方法时。

无关的,可以大大缩短你的方法:

 公共静态INT addTwoEach(PARAMS INT []参数)
{
    返回args.Sum()+ 2 * args.Length;
}

I know this is a basic question, but I couldn't find an answer.

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:

With params:

static public int addTwoEach(params int[] args)
{
    int sum = 0;
    foreach (var item in args)
        sum += item + 2;
    return sum;
}

Without params:

static public int addTwoEach(int[] args)
{
    int sum = 0;
    foreach (var item in args)
       sum += item + 2;
    return sum;
}

解决方案

With params you can call your method like this:

addTwoEach(1, 2, 3, 4, 5);

Without params, you can’t.

Additionally, you can call the method with an array as a parameter in both cases:

addTwoEach(new int[] { 1, 2, 3, 4, 5 });

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆