简体   繁体   中英

How can I call a delegate that takes multiple parameters if I have a list of mixed type that matches the delegate parameter pattern?

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? eg

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM