2012-03-02 110 views

回答

60

是的。最典型的例子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); 
} 

http://msdn.microsoft.com/en-us/library/dd264739.aspx

+0

如何通过RPC传递参数从Java与JSON数据格式? – 2016-10-04 12:53:13

10

是,params

public void SomeMethod(params object[] args) 

PARAMS必须是最后一个参数,可以是任何类型的。不知道它是否必须是一个数组或只是一个IEnumerable。

12

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

下面是一个例子。

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

还有更多的信息here

6

我假定你的意思是variable number of method parameters。如果是这样的:

void DoSomething(params double[] parms) 

(或者具有固定参数混合)

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

限制:

  • 他们都必须是同一类型(或子类)的是真正的数组
  • 每个方法只能有一个
  • 它们必须在参数li st

这就是我现在所能想到的,尽管可能有其他人。检查文档以获取更多信息。

相关问题