调用泛型事件发生时的方法 [英] Call a method when a generic event occurs

查看:224
本文介绍了调用泛型事件发生时的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试实现一个对运行时定义的事件触发的方法的调用时遇到问题。我发现这个答案:

I'm facing a problem when trying to implement a call to a method fired up by an event which should be defined during run-time. I found this answer:

从通用事件处理程序重定向到动态方法

并实现了该解决方案,但是当我调用方法是一个实例,而不是静态。
这是我的部分代码:

and implemented that solution, but I keep getting an exception when the method to call is an instance one, not static. Here is my partial code:

public class Operation
{
    public bool EventFired 
    {
        get { return _eventFired; }
    }

    private bool _eventFired = false;

    public void Execute(object source, string EventName)
    {
        EventInfo eventInfo = source.GetType().GetEvent(EventName);
        Delegate handler = null;

        Type delegateHandler = eventInfo.EventHandlerType;
        MethodInfo invokeMethod = delegateHandler.GetMethod("Invoke");
        ParameterInfo[] parms = invokeMethod.GetParameters();

        Type[] parmTypes = new Type[parms.Length];

        for (int i = 0; i < parms.Length; i++)
            parmTypes[i] = parms[i].ParameterType;

        DynamicMethod customMethod = new DynamicMethod
            (
            "TempMethod",
            invokeMethod.ReturnType,
            parmTypes,
            typeof (Operation).Module
            );

        MethodInfo inf = typeof (Operation).GetMethod("SetFlag", BindingFlags.Instance | BindingFlags.Public);

        ILGenerator ilgen = customMethod.GetILGenerator();
        ilgen.Emit(OpCodes.Ldarg_0);
        ilgen.Emit(OpCodes.Call, inf);
        ilgen.Emit(OpCodes.Ret);

        //handler = _customMethod.CreateDelegate(delegateHandler);          // This works if I change SetFlag() to static 

        handler = customMethod.CreateDelegate(delegateHandler, this);       // I get an ArgumentException at this point: 
                                                                            //Cannot bind to the target method because its signature 
                                                                            //or security transparency is not compatible with that of the delegate type.   



        eventInfo.AddEventHandler(source, handler);
    }

    /// <summary>Signals that the event has been raised.</summary>
    public void SetFlag()
    {
        _eventFired = true;
    }

}

我找不到方法为了摆脱这个异常,如果我将 SetFlag()方法转换成静态代码,代码就可以正常工作,但这不是我需要的。
任何建议将不胜感激。
提前感谢。

I can't find a way to get rid of that exception, the code works fine if I turn SetFlag() method to static, but that's not what I need. Any suggestions would be very appreciated. Thanks in advance.

推荐答案

我终于设法通过稍微修改DynamicMethod定义来解决问题,如这个答案所述:

I finally managed to resolve the problem by slightly modifying the DynamicMethod definition, as described in this answer:

在动态中引用this事件处理程序

如果我将类类型添加到类型数组中的第一个值,然后将其作为参数传递给DynamicMethod,代理正确创建,它与实例方法一起使用!

If I add my class type as first value in the Type array, which is then passed as parameter to the DynamicMethod, the delegate is correctly created and it works with instance methods!

public class Operation
{
    public bool EventFired 
    {
        get { return _eventFired; }
    }

    private bool _eventFired = false;

    public void Execute(object source, string EventName)
    {
        EventInfo eventInfo = source.GetType().GetEvent(EventName);
        Delegate handler = null;

        Type delegateHandler = eventInfo.EventHandlerType;
        MethodInfo invokeMethod = delegateHandler.GetMethod("Invoke");
        ParameterInfo[] parms = invokeMethod.GetParameters();

        Type[] parmTypes = new Type[parms.Length + 1];

        parmTypes[0] = this.GetType();  //First parameter is this class type.

        for (int i = 0; i < parms.Length; i++)
            parmTypes[i + 1] = parms[i].ParameterType;

        DynamicMethod customMethod = new DynamicMethod
                                    (
                                        "TempMethod",
                                        invokeMethod.ReturnType,
                                        parmTypes
                                    );

        MethodInfo inf = typeof (Operation).GetMethod("SetFlag", BindingFlags.Instance | BindingFlags.Public);

        ILGenerator ilgen = customMethod.GetILGenerator();
        ilgen.Emit(OpCodes.Ldarg_0);
        ilgen.Emit(OpCodes.Call, inf);
        ilgen.Emit(OpCodes.Ret);

        handler = customMethod.CreateDelegate(delegateHandler, this);      

        eventInfo.AddEventHandler(source, handler);
    }

    /// <summary>Signals that the event has been raised.</summary>
    public void SetFlag()
    {
        _eventFired = true;
    }

}

这篇关于调用泛型事件发生时的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆