2010-06-11 2 views

Antwort

58

Verwendung 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); 

Für eine Action<T> etc, geben Sie einfach die entsprechende Delegattyp überall.

In .NET Core Delegate.CreateDelegate nicht existiert, aber MethodInfo.CreateDelegate tut:

// Static method 
Action action = (Action) method.CreateDelegate(typeof(Action)); 

// Instance method (on "target") 
Action action = (Action) method.CreateDelegate(typeof(Action), target); 
+0

upvoted. Wie wendet man das auf DataEventArgs an? http://stackoverflow.com/questions/33376326/how-to-create-generic-event-delegate-from-methodinfo –

+0

'Delegate.CreateDelegate' scheint nicht in .Net Core verfügbar. Irgendwelche Ideen da? – IAbstract

+0

@IAbstract: Interessant - das hatte ich nicht bemerkt. Sie können stattdessen 'MethodInfo.CreateDelegate' aufrufen. (Probieren Sie es einfach aus, und es hat gut geklappt.) –

0

Dies scheint auch auf der Johns Beratung zu arbeiten:

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