开发者

Hook-up a MethodInfo to a delegate field (FieldInfo)

开发者 https://www.devze.com 2023-03-14 09:25 出处:网络
Simple case: public class MyClass { public Action<double> MyAction; } public class AnotherClass { public void MyAction(double value)

Simple case:

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

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

As I get both AnotherClass.MyAction(..) method and MyClass.MyAction delegate through reflection, I end up with a pair of MethodInfo/FieldInfo classes where I can't hookup the method to the delegate. Also I get both the method/delegate names from a string, I can't access the instance fields/methods without reflection. Can anyone give me a hand in 开发者_StackOverflow中文版this, or is this sort of a hook-up possible at all?


You should look at Delegate.CreateDelegate, in particular:

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消