是否有 C# 替代 Java 的 vararg 参数?

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

Is there a C# alternative to Java's vararg parameters?

c#

提问by Pradeep K M

I have worked on Java and new to .Net technology

我从事过 Java 和 .Net 技术的新手工作

Is it possible to declare a function in C# which accepts variable input parameters

是否可以在 C# 中声明一个接受可变输入参数的函数

Is there any C# syntax similar to the following Java syntax?

是否有任何类似于以下 Java 语法的 C# 语法?

void f1(String... a)

回答by Jon Skeet

Yes, C# has an equivalent of varargs parameters. They're called parameter arrays, and introduced with the paramsmodifier:

是的,C# 有一个相当于可变参数的参数。它们被称为参数数组,并通过params修饰符引入:

public void Foo(int x, params string[] values)

Then call it with:

然后调用它:

Foo(10, "hello", "there");

Just as with Java, it's only the last parameter which can vary like this. Note that (as with Java) a parameter of params object[] objectscan easily cause confusion, as you need to remember whether a single argument of type object[]is meant to be wrapped again or not. Likewise for any nullable type, you need to remember whether a single argument of nullwill be treated as an array reference or a single array element. (I thinkthe compiler only creates the array if it has to, but I tend to write code which avoids me having to remember that.)

就像 Java 一样,它只是最后一个可以像这样变化的参数。请注意(与 Java 一样)的参数params object[] objects很容易引起混淆,因为您需要记住类型的单个参数object[]是否打算再次包装。同样,对于任何可为 null 的类型,您需要记住是将 的单个参数null视为数组引用还是单个数组元素。(我认为编译器只在必要时创建数组,但我倾向于编写代码以避免我必须记住这一点。)

回答by Adriaan Stander

Have a look at params (C# Reference)

看看params (C# 参考)

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

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 关键字后不允许附加参数,并且方法声明中只允许一个 params 关键字。

As shown in the example the method is declared as

如示例所示,该方法声明为

public static void UseParams(params int[] list)
{
    for (int i = 0; i < list.Length; i++)
    {
        Console.Write(list[i] + " ");
    }
    Console.WriteLine();
}

and used as

并用作

UseParams(1, 2, 3, 4);