gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:53:01 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com