将多个可选参数传递给C#函数 [英] Pass multiple optional parameters to a C# function

查看:137
本文介绍了将多个可选参数传递给C#函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法设置一个C#函数来接受任意数量的参数?例如,你可以设置一个函数,使得以下所有工作 -

  x = AddUp(2,3)

x = AddUp(5,7,8,2)

x = AddUp(43,545,23,656,23,64,234,44)
< code $ <$ $ p

解决方案使用参数数组 c> params 修饰符:

  public static int AddUp(params int [] values)
{
int sum = 0;
foreach(int值中的值)
{
sum + = value;
}
回报金额;

如果您想确保至少有 值(而不是一个可能为空的数组),然后分别指定:

  public static int AddUp(int firstValue,params int [ ]值)

(Set sum to firstValue ,以在实现中开始。)

请注意,您还应该检查常规数组引用的无效性办法。在该方法中,该参数是一个完美的普通数组。当您调用该方法时,参数数组修饰符只会有所不同。基本上,编译器会变成:

pre $ int c = AddUp(4,5,6);

类似于:

  int [] tmp = new int [] {4,5,6}; 
int x = AddUp(tmp);

You can 可以用一个完全正常的数组来调用它 - 所以后者语法在源代码中也是有效的。


Is there a way to set up a C# function to accept any number of parameters? For example, could you set up a function such that the following all work -

x = AddUp(2, 3)

x = AddUp(5, 7, 8, 2)

x = AddUp(43, 545, 23, 656, 23, 64, 234, 44)

解决方案

Use a parameter array with the params modifier:

public static int AddUp(params int[] values)
{
    int sum = 0;
    foreach (int value in values)
    {
        sum += value;
    }
    return sum;
}

If you want to make sure there's at least one value (rather than a possibly empty array) then specify that separately:

public static int AddUp(int firstValue, params int[] values)

(Set sum to firstValue to start with in the implementation.)

Note that you should also check the array reference for nullity in the normal way. Within the method, the parameter is a perfectly ordinary array. The parameter array modifier only makes a difference when you call the method. Basically the compiler turns:

int x = AddUp(4, 5, 6);

into something like:

int[] tmp = new int[] { 4, 5, 6 };
int x = AddUp(tmp);

You can call it with a perfectly normal array though - so the latter syntax is valid in source code as well.

这篇关于将多个可选参数传递给C#函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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