You'll need to use Type.GetMethod
to get the right method, and Delegate.CreateDelegate
to convert the MethodInfo
into a delegate. Full example:
using System;
using System.Reflection;
delegate string MyDelegate();
public class Dummy
{
public override string ToString()
{
return "Hi there";
}
}
public class Test
{
static MyDelegate GetByName(object target, string methodName)
{
MethodInfo method = target.GetType()
.GetMethod(methodName,
BindingFlags.Public
| BindingFlags.Instance
| BindingFlags.FlattenHierarchy);
// Insert appropriate check for method == null here
return (MyDelegate) Delegate.CreateDelegate
(typeof(MyDelegate), target, method);
}
static void Main()
{
Dummy dummy = new Dummy();
MyDelegate del = GetByName(dummy, "ToString");
Console.WriteLine(del());
}
}
Mehrdad's comment is a great one though - if the exceptions thrown by this overload of Delegate.CreateDelegate are okay, you can simplify GetByName
significantly:
static MyDelegate GetByName(object target, string methodName)
{
return (MyDelegate) Delegate.CreateDelegate
(typeof(MyDelegate), target, methodName);
}
I've never used this myself, because I normally do other bits of checking after finding the MethodInfo
explicitly - but where it's suitable, this is really handy :)