I have a method that contains a delegate variable that points at another class. I want to call a method in that class via this delegate, but pass the name of the method as a string to the method containing the delegate.
How can this be done? Using reflection? Func<T>
?
Edit:
I understand now that reflection may not be the best solution.
This is what I have:
private static void MethodContainingDelegate(string methodNameInOtherClassAsString)
{
_listOfSub.ForEach(delegate(Callback callback)
{
//Here the first works, but I want the method to be general and
// therefore pass the method name as a string, not specfify it.
callback.MethodNameInOtherClass();
//This below is what I am trying to get to work.
callback.MethodNameInOtherClassAsString();
}
});
}
So, basically, I am looking for a way to make my callback delegate "recognize" that my methodNameInOtherClassAsString is actually a method to execute in the other class.
Thanks!
It's very simple:
It doesn't matter, what class does the delegate variable point to. It can be defined in another class -- there's not much difference.
I think you could even query the name of the original method from the delegate variable itself without reflection. Every delegate has a property called
Method
exactly for that.Assuming you have string representation of the method name:
you need to add some error checking to this obviously, and should use a more specific version of GetMethod if you can.
You can do something like this:
Where Foo is your target class, Bar is the method you want to call. But you should note that reflection will have a great impact on your program's performance. Consider using strongly typed delegates instead.