Is it possible to connect an anonymous delegate using reflection?

From this MSDN article, there are several ways to connect a delegate that uses reflection.

It seems the best way is with the CreateDelegate method:

Delegate d = Delegate.CreateDelegate(delegateType, targetObject, handlerMethodName);

Under normal circumstances, I would point to a handler method that resides in the targetObject class. But what if a delegate was created anonymously? Example:

public delegate void SelectedVehiclesCollectionDelegate(string query, List<Vehicles> list);
...
myObject.SelectedVehiclesCollection = (query, list) =>
                    {
                      //assign list of vehicles to list matching query
                    };  

There is no method in the definition of the class that the delegate refers to. I need to call this delegate, which is unknown at runtime, resulting in a list of items.

Well, it looks like my terminology got the best of me. I did not seek to create a handler, but referred to what already happened (Thomas Petrichek’s answer still gives me some idea).

+3
2

, , , , Delegate.DynamicInvoke - , , , 're after, .

, , :

MyDelegate handler = (MyDelegate) propertyInfo.GetValue(obj, null);
handler(...); // Call as normal
+2

, . - , .

Reflection, :

class Closure {
  public Action Operation { get; set; }
  public void Invoke() { Operation(); }
}

, - ( Invoke ):

var op = new Closure { Operation = delegate() { .. } };

, - Reflection , - , . (, Action), . , , .

+1

Source: https://habr.com/ru/post/1795489/


All Articles