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

本文关键字:支持 何支持 参数 是否 | 更新日期: 2023-09-27 18:26:18

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

如果是,C#如何支持变量no of arguments?

有哪些例子?

变量参数如何有用?

第1版:有哪些限制?

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

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

是。经典的例子是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

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

下面是一个例子。

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

这里有更多信息。

是,参数:

public void SomeMethod(params object[] args)

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

我假设你指的是数量可变的方法参数。如果是:

void DoSomething(params double[] parms)

(或与固定参数混合)

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

限制:

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

这就是我目前所能想到的,尽管可能还有其他人。有关详细信息,请查看文档。