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?
Yes, it is possible, as long as you use Linq Expressions, and little reflection.
Take a look at this code, it does something simillar to what I think you want: