Reputation: 81
There is a set of methods like:
Foo(int, float, params objects[])
Goo(int, params objects[])
Too()
each taking different number of & type of parameters (so are return values).
I read an integer (an index) from a database. The integer corresponds to one of the above method (1 for Foo, 2 for Goo and 3 for Too).
How do I store above methods (as delegates) in a collection so that I can call appropriate method by indexing into the collection using the integer read from db as index.
Upvotes: 2
Views: 8616
Reputation: 30790
Store the methods as Delegate
inside a List or Array and use DynamicInvoke
to call them - note that you will need to pass the correct number (and type) of variables.
var delegates = new List<Delegate>();
delegates.Add((Action<int, float, object[]>)Foo);
//...
delegates[0].DynamicInvoke(new[] {0, 1.2, new object()});
This solution is best suited when you want to pass default (read: zero/null) to the methods - then you can use reflection to create the default values.
Another useful case is if you want to call a specific method signature (i.e. a method that receives a single int) then you can go to the desired index and check (using reflection) if the delegate can be called with that argument.
Otherwise you need to have some knowledge of the method you're calling because each method has different argument type and number.
Upvotes: 6
Reputation: 1038890
As the three methods have different number of arguments and types in order to call them you will need to know in which case you are, so the ifs
are inevitable. IMHO there will be no benefit to hold an array of delegates.
switch (index) {
case 1: // call method1
break;
case 2: // call method2
break;
case 3: // call method3
break;
}
Upvotes: 4
Reputation: 1500795
You could just use a Delegate[]
- when you read the integer, you'll then need to cast the relevant array value to an Action<int, float, object[]>
, an Action<int, object[]>
or an Action
before you call it though.
Upvotes: 8
Reputation: 50273
I would suggest using a dictionary where the key is the index and the value is the delegate. However the methods have different signatures, so you will not be able to directly use them interchangeably. By the way where would you take the parameters for the methods when calling them?
Upvotes: 0