简单案例:
public class MyClass
{
public Action<double> MyAction;
}
public class AnotherClass
{
public void MyAction(double value)
{
// ...
}
}
当我通过反射获得AnotherClass.MyAction(..)
方法和MyClass.MyAction
委托时,我最终得到了一对MethodInfo/FieldInfo类,在这些类中我无法将方法连接到委托。此外,我从字符串中获得方法/委托名称,如果没有反射,我无法访问实例字段/方法。有人能帮我一把吗?或者这种勾搭可能吗?
您应该查看Delegate.CreateDelegate
,特别是:
MethodInfo method = typeof(AnotherClass).GetMethod("MyAction");
FieldInfo field = typeof(MyClass).GetField("MyAction");
AnotherClass obj = // the object you want to bind to
Delegate action = Delegate.CreateDelegate(field.FieldType, obj, method);
MyClass obj2 = // the object you want to store the delegate in
field.SetValue(obj2, action);