包含方法的数组

Rub*_*ers 14 c# arrays methods

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

谢谢

Pet*_*ton 14

你去吧

List<Action> list = new List<Action>();
list.Add( () => ClassA.MethodX(paramM) );
list.Add( () => ClassB.MethodY(paramN, ...) );

foreach (Action a in list) {
    a.Invoke();
}
Run Code Online (Sandbox Code Playgroud)

  • @Vilx- 是的,您可以使用 `a()`。并且您不需要为此使用繁重的`List&lt;T&gt;`。你可以做`new Action[] { ()=&gt; MyMethod(), ()=&gt; MyMethod2() };` (2认同)

Jen*_*ens 7

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

List<Func<T1, T2, TReturn>>
Run Code Online (Sandbox Code Playgroud)

类型的实例Func<T1, T2, TReturn>是类似的方法

TReturn MyFunction(T1 input1, T2 input2)
Run Code Online (Sandbox Code Playgroud)

看一下MSDN.