C#是否支持可变数量的参数,以及如何?

时间:2012-03-02 05:08:09

标签: c# .net variables arguments params

C#是否支持可变数量的参数?

如果是,C#如何支持变量no参数?

有什么例子?

变量参数如何有用?

编辑1 :对它有什么限制?

编辑2 :问题不是关于可选参数而是变量参数

4 个答案:

答案 0 :(得分:66)

是。经典的例子是params object[] args

//Allows to pass in any number and types of parameters
public static void Program(params object[] args)

典型的用例是将命令行环境中的参数传递给程序,在程序中将它们作为字符串传递。然后程序可以正确验证和分配它们。

限制:

  • 每种方法只允许一个params个关键字
  • 必须是最后一个参数。
编辑:在我阅读你的编辑后,我成了我的。下面的部分还介绍了实现可变数量参数的方法,但我认为您确实在寻找params方式。


也是比较经典的一种,称为方法重载。你可能已经经常使用它们了:

//both methods have the same name and depending on wether you pass in a parameter
//or not, the first or the second is used.
public static void SayHello() {
    Console.WriteLine("Hello");
}
public static void SayHello(string message) {
    Console.WriteLine(message);
}

最后但并非最不重要的一个:可选参数

//this time we specify a default value for the parameter message
//you now can call both, the method with parameter and the method without.
public static void SayHello(string message = "Hello") {
    Console.WriteLine(message);
}

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

答案 1 :(得分:14)

C#支持使用params关键字的可变长度参数数组。

这是一个例子。

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

还有更多信息here

答案 2 :(得分:11)

是的,params

public void SomeMethod(params object[] args)

params必须是最后一个参数,可以是任何类型。不确定它是否必须是数组或IEnumerable。

答案 3 :(得分:7)

我认为你的意思是variable number of method parameters。如果是这样的话:

void DoSomething(params double[] parms)

(或与固定参数混合)

void DoSomething(string param1, int param2, params double[] otherParams)

限制:

  • 它们必须是同一类型(或子类型),对于数组也是如此
  • 每个方法只能有一个
  • 他们必须在参数列表
  • 中排在最后

尽管可能还有其他人,但我现在才能想到这一切。有关详细信息,请查看文档。