Is it possible to hook up a anonymous Delegate using reflection?
From this MSDN article, there's quite a few ways to hook up a delegate using reflection.
It seems the best way is with the CreateDelegate method:
Delegate d = Delegate.CreateDelegate(delegateType, targetObject, handlerMethodName);
Under normal circumstances, I'd be pointing to the handler method that is within the targetObject class. But what if the 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's not a method within the class definition to which the delegate is referencing. I need to invoke this delegate which is开发者_如何学Python unknown at runtime, obtaining the list of items are a result.
Ok, looks like my terminology got the best of me. Wasnt aiming at creating a handler but invoke what's already there (Tomas Petricek's answer still gives me some good insight though).
Given your comment, it sounds like this is about calling a delegate rather than creating one, in which case Delegate.DynamicInvoke
is probably what you're after, if you really don't know the relevant delegate type at compile time.
If you do know the relevant delegate type, just not the property name, you can cast:
MyDelegate handler = (MyDelegate) propertyInfo.GetValue(obj, null);
handler(...); // Call as normal
Under the cover, the anonymous delegate is compiled into a class, so there is still some target object and method name. The class can contain some additional fields as well - if you capture a local variable inside the method, it becomes a member of the class.
If you want to have a simple way to create anonymous delegates and hook them up using Reflection, you can write a very simple class:
class Closure {
public Action Operation { get; set; }
public void Invoke() { Operation(); }
}
Then you can create an operation using something like this (and use Invoke
as the target method):
var op = new Closure { Operation = delegate() { .. } };
It depends on what exactly are you trying to do - the point of hooking events using Reflection is that you just have some method that you want to run. If you have a delegate (e.g. Action
) then you can use it directly. A class like this may be useful if you want to create a delegate unknown at compile time.
精彩评论