Connecting 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 the AnotherClass.MyAction(..) method and the MyClass.MyAction delegate MyClass.MyAction through reflection, I get a couple of MethodInfo / FieldInfo classes where I cannot connect the method to the delegate. Also I get the method / delegate names from the string, I can not access the fields / methods of the instance without reflection. Can someone give me a hand in this, or is such a connection possible?

+7
source share
1 answer

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); 
+8
source

All Articles