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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1996426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:30:36  来源:igfitidea点击:

Pass multiple optional parameters to a C# function

c#functionparameters

提问by Craig Schwarze

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)

采纳答案by Jon Skeet

Use a parameter arraywith the paramsmodifier:

使用带有修饰符的参数数组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 onevalue (rather than a possibly empty array) then specify that separately:

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

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

(Set sumto firstValueto start with in the implementation.)

(在实现中设置sumfirstValue开始。)

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 callthe 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 cancall it with a perfectly normal array though - so the latter syntax is valid in source code as well.

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

回答by Tarydon

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

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

回答by Pit J

1.You can make overload functions.

1.您可以制作重载功能。

SomeF(strin s){}   
SomeF(string s, string s2){}    
SomeF(string s1, string s2, string s3){}   

More info: http://csharpindepth.com/Articles/General/Overloading.aspx

更多信息:http: //csharpindepth.com/Articles/General/Overloading.aspx

2.or you may create one function with params

2.或者你可以用参数创建一个函数

SomeF( params string[] paramArray){}
SomeF("aa","bb", "cc", "dd", "ff"); // pass as many as you like

More info: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params

更多信息:https: //docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params

3.or you can use simple array

3.或者你可以使用简单的数组

Main(string[] args){}