开发者

Array containing Methods

开发者 https://www.devze.com 2023-04-12 11:52 出处:网络
I was wondering if you can create an Array or a Li开发者_开发技巧st<> that contains methods. I don\'t want to use a switch or lots of if statements.

I was wondering if you can create an Array or a Li开发者_开发技巧st<> that contains methods. I don't want to use a switch or lots of if statements.

Thanks


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();
}


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.


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.


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
}


object[] arrProc = new object[2];

arrProc[0] = (string)Fx1();

arrProc[1] = (string)Fx2();

string aa = (string)arrProc[0];

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号