How to attach event handler to an event using reflection?

前端 未结 1 1966
情深已故
情深已故 2021-01-02 08:38

I know about EventInfo.AddEventHandler(...) method which can be used to attach handler to an event. But what should be done if i can not even define proper sign

1条回答
  •  生来不讨喜
    2021-01-02 09:03

    I think your code is failing because the HandleRfqSendComment is private. Instead you could directly create a delegate to that method, without passing its name to CreateDelegate. You would then need to convert the delegate to the required type, using the following method :

    public static Delegate ConvertDelegate(Delegate originalDelegate, Type targetDelegateType)
    {
        return Delegate.CreateDelegate(
            targetDelegateType,
            originalDelegate.Target,
            originalDelegate.Method);
    }
    

    In your code, you could use this method as follows :

    EventInfo eventInfo = rfqWindowManager.GetType().GetEvent("SendComment");
    Action handler = HandleRfqSendComment;
    Delegate convertedHandler = ConvertDelegate(handler, eventInfo.EventHandlerType);
    eventInfo.AddEventHandler(rfqWindowManager, convertedHandler);
    

    0 讨论(0)
提交回复
热议问题