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

标签 c# .net variables arguments parameters

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

如果是,C# 是如何支持变量个数的?

有哪些例子?

变量参数有什么用?

编辑 1:它有哪些限制?

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

最佳答案

是的。典型的例子是 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# - C# 是否支持可变数量的参数,如何支持?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9528276/

相关文章:

c# - 如何测试 Action<...> 是否为空?

c# - 使用 ASP.NET Identity 创建默认用户帐户

c# - Azure Functions 中 local.settings.json 的值

c# - 正则表达式性能下降

PHP 在 session 变量中传递数组

bash - 为什么 shell 会忽略通过变量传递给它的参数中的引号字符?

MySql 查询中的 PHP 变量

c# - 什么会使 PerformanceCounterCategory.Exists 无限期挂起?

asp.net - 检查Web服务是否存在

c# - 多部分 int 字典键的最佳方法?