DynamicMethod 및 Ilgenerator를 사용하여 C#의 동적 이벤트 생성

StackOverflow https://stackoverflow.com/questions/674728

  •  21-08-2019
  •  | 
  •  

문제

런타임에서 eventInfo 객체를 기반으로 이벤트 핸들러를 생성하고 해당 이벤트 핸들러 내에서 메소드를 호출해야합니다. 다음과 같은 것 :

public void RegisterAction(ActionData actionData, EventInfo eventInfo, 
    Control control)
{
    MethodInfo methodInfo = eventInfo.EventHandlerType.GetMethod("Invoke");

    List<Type> ps = new List<Type>();
    foreach (ParameterInfo info in methodInfo.GetParameters())
    {
        ps.Add(info.ParameterType);
    }

     DynamicMethod method = new DynamicMethod("Adapter",
                                              typeof (void),
                                              ps.ToArray(),
                                              GetType(), 
                                              true);

     ILGenerator generator = method.GetILGenerator();

     // Here I need to generate a method to do the following:
     // ExecuteAction(actionData);

     // Then I can use this runtime method as an event handler and
     // bind it to the control
     Delegate proxy = method.CreateDelegate(eventInfo.EventHandlerType, this);

     eventInfo.AddEventHandler(control, proxy);
}

주석 부분에 대한 IL 코드를 생성하는 데 도움이 필요합니다.

도움이 되었습니까?

해결책

public void RegisterAction(ActionData actionData, EventInfo eventInfo, 
    Control control)
{
    MethodInfo methodInfo = eventInfo.EventHandlerType.GetMethod("Invoke");

    List<Type> ps = new List<Type>();
    ps.Add  (typeof (ActionData)) ;
    foreach (ParameterInfo info in methodInfo.GetParameters())
    {
        ps.Add(info.ParameterType);
    }

     DynamicMethod method = new DynamicMethod("Adapter",
                                              typeof (void),
                                              ps.ToArray(),
                                              GetType(), 
                                              true);

     // compatible signatures for ExecuteAction
     // (assuming you aren't interested in sender and eventArgs):
     // static void ExecuteAction (ActionData) ;
     // void ActionData.ExecuteAction () ;
     MethodInfo miExecuteAction = <...> ;
     ILGenerator generator = method.GetILGenerator();
     generator.Emit (OpCodes.Ldarg_0) ;
     generator.Emit (OpCodes.Call, miExecuteAction) ;
     generator.Emit (OpCodes.Ret) ;

     // if you want to pass this to ExecuteAction, 
     // you'll need to put it into actionData.
     Delegate proxy = method.CreateDelegate(eventInfo.EventHandlerType, actionData);

     eventInfo.AddEventHandler(control, proxy);
}

편집하다: 모든 이벤트가 (발신자, Args) 패턴을 따르면 SRE를 엉망으로 만들 필요조차 없습니다.

public static void Execute<T> (ActionData data, object sender, T args)
    where T : EventArgs
{
    ExecuteAction (data) ;
}

public void RegisterAction (ActionData actionData, EventInfo eventInfo, 
    Control control)
{
    MethodInfo compatibleMethod = typeof (this).GetMethod ("Execute",
        BindingFlags.Static | BindingFlags.Public).MakeGenericMethod (
        eventInfo.EventHandlerType.GetMethod ("Invoke").GetParameters ()[1].ParameterType)) ;
    eventInfo.AddEventHandler (control, 
        Delegate.CreateDelegate (eventInfo.EventHandlerType, actionData,
        compatibleMethod)) ;
}

다른 팁

나는 당신이 당신의 이벤트의 Methodinfo에서 대의원을 만들고 싶다고 생각합니다 ...

그렇다면, 여기에 기사가 있습니다 이것에 관한 방법을 설명합니다. 필요한 IL 코드는 해당 기사에 설명되어 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top