rookie
rookie

Reputation: 2923

Function dictionary without specifying parameters

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

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

I apologize if this question has been asked already -- I wasn't sure what to search for.

Upvotes: 4

Views: 1025

Answers (1)

Adriano Repetti
Adriano Repetti

Reputation: 67128

Yes, use Delegate instead of typed function. You'll call them with DynamicInvoke() and parameters can be passed with an array. In short:

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 it:

CallIt("test1", 1);
CallIt("test2", 1, 2);

Upvotes: 3

Related Questions