Function dictionary without parameters

I have a dictionary that uses strings as keys and Actionfunctions as values.

Is there a way to define a dictionary without specifying the parameters of each key function? For example, let's say I have a function foo(int a, string b). Can I appoint dict['test'] = foo?

I apologize if this question has already been asked - I was not sure what to look for.

+4
source share
1 answer

Yes, use Delegatea typed function instead. You will call them using DynamicInvoke(), and the parameters can be passed using an array. Shortly speaking:

Dictionary<string, Delegate>() _delegates;

void Test1(int a) { }
void Test2(int a, int b) { }

void SetUp() {
    _delegates = new Dictionary<string, Delegate>();
    _delegates.Add("test1", Test1);
    _delegates.Add("test2", Test2);
}

void CallIt(string name, params object[] args) {
    _delegates[name].DynamicInvoke(args);
}

Try:

CallIt("test1", 1);
CallIt("test2", 1, 2);
+3
source

Source: https://habr.com/ru/post/1536471/


All Articles