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

Teo*_*gul 8 c# reflection delegates

简单案例:

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

public class AnotherClass
{
  public void MyAction(double value)
  {
    // ...
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ell 10

你应该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);
Run Code Online (Sandbox Code Playgroud)