Array containing Methods

2020-02-12 00:43发布

问题:

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
}