Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 this, or is this sort of a hook-up possible at all?

like image 234
Teoman Soygul Avatar asked Jun 22 '11 07:06

Teoman Soygul


1 Answers

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);
like image 152
Marc Gravell Avatar answered Oct 22 '22 22:10

Marc Gravell