2010-06-11 69 views

回答

58

使用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); 

對於Action<T>等,只是到處指定適當的委託類型。

在.NET中的核心,Delegate.CreateDelegate不存在,但MethodInfo.CreateDelegate的作用:

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

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

Upvoted。如何將此應用於DataEventArgs ? http://ntackoverflow.com/questions/33376326/how-to-create-generic-event-delegate-from-methodinfo – 2015-10-27 18:57:56

+0

'Delegate.CreateDelegate'似乎在.Net Core中不可用。那裏有任何想法? – IAbstract 2017-05-05 13:41:08

+0

@IAbstract:有趣 - 我沒有發現。您可以改爲調用'MethodInfo.CreateDelegate'。 (剛剛嘗試過,它運行良好。) – 2017-05-05 13:48:51

0

這似乎對約翰的建議基礎上工作過:

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