Reputation: 433
I'm writing a simple interpreter.
For function calls I have a hashtable that stores delegates, with the function name as the key. When I retrieve a delegate, I can check that the correct parameter types have been input and parsed to pass to the function.
However, these parameters are in a list of mixed type and the delegate parameters are declared normally. How can I call any of the delegates with this list of parameters? e.g.
private Dictionary<string, Delegate> _functions = new Dictionary<String, Delegate>();
public string exFunc(int num, string text)
{
return num;
}
AddToDictionary(exFunc); //this is a method that calculates the correct delegate signature for any method and adds to _functions
List<paramTypes> parameters = new List<paramTypes>() {5,"hello"};
Delegate d = _functions["exFunc"];
Is there a way to do something like the following, given that the delegate parameter signature has been checked so that the list of parameters has the correct types?:
var res = d(ToSingleParams(parameters));
I looked into the "params" keyword but it is only for arrays of a single type that I can tell.
Thanks for any help!
Upvotes: 0
Views: 2137
Reputation: 7458
Converting my comment to answer. You need to use DynamicInvoke method to call it dynamically. It has params object[]
parameter that can be used for method parameters. In your sample it would be like this:
private Dictionary<string, Delegate> _functions = new Dictionary<String, Delegate>();
public string exFunc(int num, string text)
{
return num;
}
AddToDictionary(exFunc); //this is a method that calculates the correct delegate signature for any method and adds to _functions
List<paramTypes> parameters = new List<paramTypes>() {5,"hello"};
Delegate d = _functions["exFunc"];
d.DynamicInvoke(parameters.ToArray());
And here is working sample with DynamicInvoke
- https://dotnetfiddle.net/n01FKB
Upvotes: 3