Je souhaite obtenir un délégué d'action à partir d'un objet MethodInfo. Est-ce possible?Comment puis-je créer un délégué d'action à partir de MethodInfo?
Merci.
Je souhaite obtenir un délégué d'action à partir d'un objet MethodInfo. Est-ce possible?Comment puis-je créer un délégué d'action à partir de MethodInfo?
Merci.
Utilisation Delegate.CreateDelegate:
// Static method
Action action = (Action) Delegate.CreateDelegate(typeof(Action), method);
// Instance method (on "target")
Action action = (Action) Delegate.CreateDelegate(typeof(Action), target, method);
Pour un Action<T>
etc, tout simplement spécifier le type de délégué approprié partout.
Dans .NET Core Delegate.CreateDelegate
n'existe pas, mais MethodInfo.CreateDelegate
fait:
// Static method
Action action = (Action) method.CreateDelegate(typeof(Action));
// Instance method (on "target")
Action action = (Action) method.CreateDelegate(typeof(Action), target);
Cela semble fonctionner au-dessus de l'avis de John aussi:
public static class GenericDelegateFactory
{
public static object CreateDelegateByParameter(Type parameterType, object target, MethodInfo method) {
var createDelegate = typeof(GenericDelegateFactory).GetMethod("CreateDelegate")
.MakeGenericMethod(parameterType);
var del = createDelegate.Invoke(null, new object[] { target, method });
return del;
}
public static Action<TEvent> CreateDelegate<TEvent>(object target, MethodInfo method)
{
var del = (Action<TEvent>)Delegate.CreateDelegate(typeof(Action<TEvent>), target, method);
return del;
}
}
upvoted. Comment l'appliquer à DataEventArgs? http://stackoverflow.com/questions/33376326/how-to-create-generic-event-delegate-from-methodinfo –
'Delegate.CreateDelegate' ne semble pas être disponible dans .Net Core. Des idées là-bas? – IAbstract
@IAbstract: Intéressant - je n'avais pas remarqué cela. Vous pouvez appeler 'MethodInfo.CreateDelegate' à la place. (Juste essayé, et il a bien fonctionné.) –