hot*_*S85 72
是.经典的例子是params object[] args
:
//Allows to pass in any number and types of parameters
public static void Program(params object[] args)
Run Code Online (Sandbox Code Playgroud)
典型的用例是将命令行环境中的参数传递给程序,在程序中将它们作为字符串传递.然后程序可以正确验证和分配它们.
限制:
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);
}
Run Code Online (Sandbox Code Playgroud)
最后但并非最不重要的是最常见的一个:可选参数
//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);
}
Run Code Online (Sandbox Code Playgroud)
http://msdn.microsoft.com/en-us/library/dd264739.aspx
rec*_*ive 15
C#支持使用params
关键字的可变长度参数数组.
这是一个例子.
public static void UseParams(params int[] list)
{
for (int i = 0; i < list.Length; i++)
{
Console.Write(list[i] + " ");
}
Console.WriteLine();
}
Run Code Online (Sandbox Code Playgroud)
还有更多的信息在这里.
Mic*_*tum 12
是的,参数:
public void SomeMethod(params object[] args)
Run Code Online (Sandbox Code Playgroud)
params必须是最后一个参数,可以是任何类型.不确定它是否必须是数组或IEnumerable.
我假设你的意思是可变数量的方法参数.如果是这样:
void DoSomething(params double[] parms)
Run Code Online (Sandbox Code Playgroud)
(或混合固定参数)
void DoSomething(string param1, int param2, params double[] otherParams)
Run Code Online (Sandbox Code Playgroud)
限制:
尽管可能还有其他人,但我现在能想到的就是这一切.有关更多信息,请查看文档.