将多个可选参数传递给C#函数

时间:2021-12-07 07:32:26

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 -

有没有办法设置C#函数来接受任意数量的参数?例如,您是否可以设置一个功能,以便以下所有工作 -

x = AddUp(2, 3)

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

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

2 个解决方案

#1


121  

Use a parameter array with the params modifier:

使用带有params修饰符的参数数组:

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.)

(将sum设置为firstValue以在实现中开始。)

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:

请注意,您还应该以正常方式检查数组引用是否为null。在该方法中,参数是完全普通的数组。参数数组修饰符仅在调用方法时有所不同。编译器基本上转向:

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.

您可以使用完全正常的数组调用它 - 因此后一种语法在源代码中也是有效的。

#2


4  

C# 4.0 also supports optional parameters, which could be useful in some other situations. See this article.

C#4.0还支持可选参数,这在其他一些情况下可能很有用。看到这篇文章。

#1


121  

Use a parameter array with the params modifier:

使用带有params修饰符的参数数组:

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.)

(将sum设置为firstValue以在实现中开始。)

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:

请注意,您还应该以正常方式检查数组引用是否为null。在该方法中,参数是完全普通的数组。参数数组修饰符仅在调用方法时有所不同。编译器基本上转向:

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.

您可以使用完全正常的数组调用它 - 因此后一种语法在源代码中也是有效的。

#2


4  

C# 4.0 also supports optional parameters, which could be useful in some other situations. See this article.

C#4.0还支持可选参数,这在其他一些情况下可能很有用。看到这篇文章。