Array containing Methods

痴心易碎 提交于 2019-12-18 05:40:12

问题


I was wondering if you can create an Array or a List<> that contains methods. I don't want to use a switch or lots of if statements.

Thanks


回答1:


There you go

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

foreach (Action a in list) {
    a.Invoke();
}



回答2:


Yes, it is possible to have such an array or list. Depending on the number of input or output parameters, you'd use something like

List<Func<T1, T2, TReturn>>

An instance of type Func<T1, T2, TReturn> is a method like

TReturn MyFunction(T1 input1, T2 input2)

Take a look at the MSDN.




回答3:


If you are trying to replace a switch then a Dictionary might be more useful than a List

var methods = new Dictionary<string, Action>()
              {
                  {"method1", () => method1() },
                  {"method2", () => method2() }
              };

methods["method2"]();

I consider this and switch statements a code smell and they can often be replaced by polymorphism.




回答4:


Maybe you want to try this if u don't want to use Lists

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
}


来源:https://stackoverflow.com/questions/7712137/array-containing-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!