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


93

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

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

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

void f1(String... a)

2
If any of the answers below answered your question, the way Stack Overflow works, you'd "accept" the answer by clicking the checkmark next to it; details here.
T.J. Crowder

Answers:


150

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

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[] objects can 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 null will be treated as an array reference or a single array element. (I think the compiler only creates the array if it has to, but I tend to write code which avoids me having to remember that.)


+1, though I would mention that (as with pretty much any other language feature), this should not be abused.
Federico Berasategui

16
@HighCore: If you're going to mention it about pretty much any other language feature, it's probably not worth mentioning :)
Jon Skeet

2
@hvd: Given that the OP appears to be a beginner, I'd rather not go into named arguments, optional parameters etc here. I see the point that you're trying to make, but I think it would add more confusion than light at the moment.
Jon Skeet

37

Have a look at params (C# Reference)

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.

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);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.