包含方法的数组

我想知道你是否可以创建一个包含方法的数组或List 。 我不想使用开关或许多if语句。

谢谢

你去吧

List list = new List(); list.Add( () => ClassA.MethodX(paramM) ); list.Add( () => ClassB.MethodY(paramN, ...) ); foreach (Action a in list) { a.Invoke(); } 

是的,可以有这样的数组或列表。 根据输入或输出参数的数量,你可以使用类似的东西

 List> 

Func类型的实例是一个类似的方法

 TReturn MyFunction(T1 input1, T2 input2) 

看一下MSDN。

如果您尝试更换开关,则Dictionary可能比List更有用

 var methods = new Dictionary() { {"method1", () => method1() }, {"method2", () => method2() } }; methods["method2"](); 

我认为这和切换语句代码气味,它们通常可以被多态性取代 。

如果你不想使用列表,也许你想尝试这个

 public Action[] methods; private void methodsInArray() { methods= new Action[2]; methods[0] = test ; methods[1] = test1; } private void test() { //your code } private void test1() { //your code }