C#是否支持可变数量的参数?C#是否支持可变数量的参数,以及如何?
如果是,C#如何支持变量no的参数?
什么是例子?
变量参数如何有用?
编辑1:它有什么限制?
编辑2:这个问题是不是可选PARAM但变量帕拉姆
C#是否支持可变数量的参数?C#是否支持可变数量的参数,以及如何?
如果是,C#如何支持变量no的参数?
什么是例子?
变量参数如何有用?
编辑1:它有什么限制?
编辑2:这个问题是不是可选PARAM但变量帕拉姆
是的。最典型的例子wourld是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);
}
是,params:
public void SomeMethod(params object[] args)
PARAMS必须是最后一个参数,可以是任何类型的。不知道它是否必须是一个数组或只是一个IEnumerable。
C#支持使用params
关键字的可变长度参数数组。
下面是一个例子。
public static void UseParams(params int[] list)
{
for (int i = 0; i < list.Length; i++)
{
Console.Write(list[i] + " ");
}
Console.WriteLine();
}
还有更多的信息here。
我假定你的意思是variable number of method parameters。如果是这样的:
void DoSomething(params double[] parms)
(或者具有固定参数混合)
void DoSomething(string param1, int param2, params double[] otherParams)
限制:
这就是我现在所能想到的,尽管可能有其他人。检查文档以获取更多信息。
如何通过RPC传递参数从Java与JSON数据格式? – 2016-10-04 12:53:13