2010-06-11 2 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://stackoverflow.com/questions/33376326/how-to-create-generic-event-delegate-from-methodinfo –

+0

'Delegate.CreateDelegate', похоже, недоступен в .Net Core. Есть идеи? – IAbstract

+0

@IAbstract: Интересно - я этого не заметил. Вместо этого вы можете вызвать 'MethodInfo.CreateDelegate'. (Просто попробовал, и все получилось нормально.) –

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

 Смежные вопросы

  • Нет связанных вопросов^_^