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:
public delegate void DelegateTypeWithParam(object param);
public delegate void DelegateTypeWithoutParam();
public void MethodWithCallbackParam(DelegateTypeWithParam callback, DelegateTypeWithoutParam callback2)
{
callback(new object());
Console.WriteLine(callback.Method.Name);
callback2();
Console.WriteLine(callback2.Method.Name);
}
// must conform to the delegate spec
public void MethodWithParam(object param) { }
public void MethodWithoutParam() { }
public void PassCallback()
{
MethodWithCallbackParam(MethodWithParam, MethodWithoutParam);
}
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.
You can do something like this:
var mi = typeof(Foo).GetMethods().Single(x => x.Name == "Bar");
mi.Invoke(foo, null);
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.
Assuming you have string representation of the method name:
var methodInfo = myObject.GetType().GetMethod(myString); //<- this can throw or return null
methodInfo.Invoke(myObject, new object[n]{parm1, pram2,...paramn});
you need to add some error checking to this obviously, and should use a more specific version of GetMethod if you can.