你需要使用
Type.GetMethod
找到正确的方法,以及
Delegate.CreateDelegate
转换
MethodInfo
成为代表。完整例子:
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());
}
}
不过,梅尔达德的评论是一个很好的评论——如果这个超负荷的
Delegate.CreateDelegate
好吧,你可以简化一下
GetByName
明显地:
static MyDelegate GetByName(object target, string methodName)
{
return (MyDelegate) Delegate.CreateDelegate
(typeof(MyDelegate), target, methodName);
}
我自己从来没有用过这个,因为我通常在找到
方法信息
明确地说——但在合适的地方,这真的很方便:)