2010-06-11 3 views

Répondre

58

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); 
+0

upvoted. Comment l'appliquer à DataEventArgs ? http://stackoverflow.com/questions/33376326/how-to-create-generic-event-delegate-from-methodinfo –

+0

'Delegate.CreateDelegate' ne semble pas être disponible dans .Net Core. Des idées là-bas? – IAbstract

+0

@IAbstract: Intéressant - je n'avais pas remarqué cela. Vous pouvez appeler 'MethodInfo.CreateDelegate' à la place. (Juste essayé, et il a bien fonctionné.) –

0

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; 
    } 
} 
Questions connexes