Is it possible to call a delegate stored in a variable by its variable name (as a string)? I guess I'd have to use reflection mechanism, but I'm not getting anywhere
Example code:
class Demo {
public delegate int DemoDelegate();
private static int One() {
return 1;
}
private static void CallDelegate(string name) {
// somehow get the value of the variable with the name
// stored in "name" and call the delegate using reflection
}
private static void CallDelegate(string name, DemoDelegate d) {
d();
}
static void main(string[] args) {
DemoDelegate one = Demo.One;
CallDelegate(one);
// this works, but I want to avoid writing the name of the variable/delegate twice:
CallDelegate("one", one);
}
}
Is this even possible? If so how?
Variables barely exist. The only way to reliably call-by-string (in this scenario) would be to store the delegates in a dictionary:
Dictionary<string, DemoDelegate> calls = new Dictionary<string, DemoDelegate>
{
{"one",one}, {"two",two}
}
Now store that dictionary somewhere (in a field, typically), and do something like:
private int CallDelegate(string name) {
return calls[name].Invoke(); // <==== args there if needed
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With