将MethodInfo连接到委托字段(FieldInfo)

时间:2011-06-22 07:11:52

标签: c# reflection delegates

简单案例:

public class MyClass
{
  public Action<double> MyAction;
}

public class AnotherClass
{
  public void MyAction(double value)
  {
    // ...
  }
}

当我通过反射获得AnotherClass.MyAction(..)方法和MyClass.MyAction委托时,我最终得到了一对MethodInfo / FieldInfo类,我无法将该方法连接到委托。此外,我从字符串中获取方法/委托名称,我无法访问没有反射的实例字段/方法。任何人都可以帮我解决这个问题,或者这种联系是否可行呢?

1 个答案:

答案 0 :(得分:9)

你应该特别注意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);