2010-06-11 8 views

Trả lời

58

Sử dụng 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); 

Đối với một Action<T> vv, chỉ cần xác định loại đại biểu thích hợp ở khắp mọi nơi.

Trong NET Core, Delegate.CreateDelegate không tồn tại, nhưng MethodInfo.CreateDelegate làm:

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

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

upvoted. Làm cách nào để áp dụng điều này cho DataEventArgs ? http://stackoverflow.com/questions/33376326/how-to-create-generic-event-delegate-from-methodinfo –

+0

'Delegate.CreateDelegate' dường như không có sẵn trong .Net Core. Có ý tưởng nào không? – IAbstract

+0

@IAbstract: Thú vị - Tôi đã không phát hiện ra điều đó. Thay vào đó, bạn có thể gọi 'MethodInfo.CreateDelegate'. (Chỉ cần thử nó, và nó làm việc tốt.) –

0

Điều này dường như làm việc trên lời khuyên của John quá:

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