C# 具有可变数量参数的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9784630/
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-09 08:50:50  来源:igfitidea点击:

Function with variable number of arguments

c#javafunction

提问by Gabber

As the title says I need to know if there is a corresponding syntax as java's ...in method parameters, like

正如标题所说,我需要知道...方法参数中是否有与 java 相应的语法,例如

void printReport(String header, int... numbers) { //numbers represents varargs
  System.out.println(header);
  for (int num : numbers) {
     System.out.println(num);
  }
}

(code courtesy of wikipedia)

(代码由维基百科提供)

采纳答案by Adriano Repetti

Yes you can write something like this:

是的,你可以这样写:

void PrintReport(string header, params int[] numbers)
{
    Console.WriteLine(header);
    foreach (int number in numbers)
        Console.WriteLine(number);
}

回答by Thorsten Dittmar

This should be

这应该是

void printReport(String header, params int[] numbers)

回答by Tokk

I believe you mean params

我相信你的意思是参数

public void printReport(string header, params int[] list) 
{
    Console.WriteLine(header);

    for (int i = 0 ; i < list.Length; i++)
    {
        Console.WriteLine(list[i]);
    }
    Console.WriteLine();
}

回答by Marius

Try using the params keyword, placed before the statement, eg

尝试使用 params 关键字,放在语句之前,例如

myFunction(params int[] numbers);

回答by Mathias Schwarz

You can declare a method to har a variable number of parameters by using the paramskeyword. Just like when using ...in Java, this will give you an array and let you call the metods with a variable number of parameters: http://msdn.microsoft.com/en-us/library/w5zay9db(v=vs.71).aspx

您可以使用params关键字声明一个方法来分配可变数量的参数。就像...在 Java 中使用时一样,这将为您提供一个数组,并让您使用可变数量的参数调用方法:http: //msdn.microsoft.com/en-us/library/w5zay9db(v=vs.71 ) .aspx

回答by Carlos Quintanilla

Yes, there is. As Adriano said you can use C# 'params' keyword. An example is the in link below:

就在这里。正如阿德里亚诺所说,您可以使用 C# 'params' 关键字。一个例子是下面的链接:

params (C# Reference)

参数(C# 参考)

http://msdn.microsoft.com/en-us/library/w5zay9db.aspx

http://msdn.microsoft.com/en-us/library/w5zay9db.aspx

"The params keyword lets you specify a method parameter that takes a variable number of arguments.

" params 关键字允许您指定一个方法参数,该参数采用可变数量的参数。

You can send a comma-separated list of arguments of the type specified in the parameter declaration, or an array of arguments of the specified type. You also can send no arguments.

您可以发送以逗号分隔的参数声明中指定类型的参数列表,或指定类型的参数数组。您也可以不发送任何参数。

No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration."

在方法声明中的 params 关键字之后不允许有额外的参数,并且在方法声明中只允许一个 params 关键字。”