通过反射c#

时间:2016-09-22 12:15:43

标签: c# reflection

美好的一天! 我的目的是实现类,它允许我们订阅和取消订阅对象(来自)事件。这是我班上的代码。

public static class EventSubscriber
{
    public static void AddEventHandler(EventInfo eventInfo, object item, Action action)
    {
        var parameters = GetParameters(eventInfo);
        var handler = GetHandler(eventInfo, action, parameters);
        eventInfo.AddEventHandler(item, handler);
    }

    public static void RemoveEventHandler(EventInfo eventInfo,
                        object item, Action action)
    {
        var parameters = GetParameters(eventInfo);
        var handler = GetHandler(eventInfo, action, parameters);
        eventInfo.RemoveEventHandler(item, handler);
    }

    private static ParameterExpression[] GetParameters(EventInfo eventInfo)
    {
        return eventInfo.EventHandlerType
          .GetMethod("Invoke")
          .GetParameters()
          .Select(parameter => Expression.Parameter(parameter.ParameterType))
          .ToArray();
    }

    private static Delegate GetHandler(EventInfo eventInfo,
                Action action, ParameterExpression[] parameters)
    {
        return Expression.Lambda(
            eventInfo.EventHandlerType,
            Expression.Call(Expression.Constant(action),
                      "Invoke", Type.EmptyTypes), parameters)
          .Compile();
    }
}

正如您在这里看到的,有2个公共方法实际上订阅和取消订阅对象(来自)事件。以下是我测试它的示例

class Program
{
    static void Main()
    {
        Test test = new Test();
        test.SubscribeTimer();
        while (true)
        {
            if(test.a == 10)
            {
                break;
            }
        }
        test.UnsubscribeTimer();
        while (true)
        {

        }
    }
}

class Test
{
    System.Timers.Timer timer;
    public int a = 0;

    public Test()
    {
        timer = new System.Timers.Timer(1000);
        timer.Start();
    }

    public void SubscribeTimer()
    {
        var eventInfo = typeof(System.Timers.Timer).GetEvent("Elapsed");
        EventSubscriber.AddEventHandler(eventInfo, timer, TimerElapsed);
        EventSubscriber.RemoveEventHandler(eventInfo, timer, TimerNotElapsed);
    }

    public void UnsubscribeTimer()
    {
        var eventInfo = typeof(System.Timers.Timer).GetEvent("Elapsed");
        EventSubscriber.AddEventHandler(eventInfo, timer, TimerNotElapsed);
        EventSubscriber.RemoveEventHandler(eventInfo, timer, TimerElapsed);
    }

    public void TimerElapsed()
    {
        Console.WriteLine("timer elapsed");
        a++;
    }

    public void TimerNotElapsed()
    {
        Console.WriteLine("timer not elapsed");
        a++;
    }
}

样本的预期行为是在开始时我们将看到消息"计时器已经过去"每秒,在第10秒之后,我们应该只看到"计时器没有过去"我们这样做,但我们仍然看到"计时器已经过去了#34;太。这意味着AddEventHandler方法有效,但RemoveEventHandler方法不起作用。

如果你能帮助我,我会很高兴的。提前谢谢。

2 个答案:

答案 0 :(得分:1)

必须将大量的源缝合在一起以获得我需要的一站式扩展方法(如果我们切换组件供应商,可以很容易地对其进行修改),以清除我们无法控制的事件上的所有现有事件处理程序

用法很简单:

thirdPartyControlInstance.ClearEventHandlers(nameof(ThirdPartyControlType.ToolClick));

以下是代码,欢迎提出任何使其更健壮/高效/清洁的建议:

public static class EventExtensions
{
    public static void ClearEventHandlers(this object obj, string eventName)
    {
        if (obj == null)
        {
            return;
        }

        var objType = obj.GetType();
        var eventInfo = objType.GetEvent(eventName);
        if (eventInfo == null)
        {
            return;
        }

        var isEventProperty = false;
        var type = objType;
        FieldInfo eventFieldInfo = null;
        while (type != null)
        {
            /* Find events defined as field */
            eventFieldInfo = type.GetField(eventName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            if (eventFieldInfo != null && (eventFieldInfo.FieldType == typeof(MulticastDelegate) || eventFieldInfo.FieldType.IsSubclassOf(typeof(MulticastDelegate))))
            {
                break;
            }

            /* Find events defined as property { add; remove; } */
            eventFieldInfo = type.GetField("EVENT_" + eventName.ToUpper(), BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic);
            if (eventFieldInfo != null)
            {
                isEventProperty = true;
                break;
            }

            type = type.BaseType;
        }

        if (eventFieldInfo == null)
        {
            return;
        }

        if (isEventProperty)
        {
            // Default Events Collection Type
            RemoveHandler<EventHandlerList>(obj, eventFieldInfo);
            // Infragistics Events Collection Type
            RemoveHandler<EventHandlerDictionary>(obj, eventFieldInfo);
            return;
        }

        if (!(eventFieldInfo.GetValue(obj) is Delegate eventDelegate))
        {
            return;
        }

        // Remove Field based event handlers
        foreach (var d in eventDelegate.GetInvocationList())
        {
            eventInfo.RemoveEventHandler(obj, d);
        }
    }

    private static void RemoveHandler<T>(object obj, FieldInfo eventFieldInfo)
    {
        var objType = obj.GetType();
        var eventPropertyValue = eventFieldInfo.GetValue(obj);

        if (eventPropertyValue == null)
        {
            return;
        }

        var propertyInfo = objType.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance)
                                  .FirstOrDefault(p => p.Name == "Events" && p.PropertyType == typeof(T));
        if (propertyInfo == null)
        {
            return;
        }

        var eventList = propertyInfo?.GetValue(obj, null);
        switch (eventList) {
            case null:
                return;
            case EventHandlerDictionary typedEventList:
                typedEventList.RemoveHandler(eventPropertyValue, typedEventList[eventPropertyValue]);
                break;
        }
    }
}

希望这对某人有帮助!

答案 1 :(得分:0)

我认为这是因为您每次都在创建一个新的处理程序:(与前一个处理程序不匹配,因此无法从调用列表中删除)

public static void RemoveEventHandler(EventInfo eventInfo,
                    object item, Action action)
{
    var parameters = GetParameters(eventInfo);
    var handler = GetHandler(eventInfo, action, parameters); // <--
    eventInfo.RemoveEventHandler(item, handler);
}

为什么要包裹Action?失去参数?由于参数的原因,无法添加/删除eventInfo.RemoveEventHandler(item, action);。如果要删除新生成的处理程序,则应在要删除它时返回该处理程序。

public static Delegate AddEventHandler(EventInfo eventInfo, object item, Action action)
{
    var parameters = GetParameters(eventInfo);
    var handler = GetHandler(eventInfo, action, parameters);
    eventInfo.AddEventHandler(item, handler);
    return handler;
}

public static void RemoveEventHandler(EventInfo eventInfo,
                    object item, Delegate handler)
{
    eventInfo.RemoveEventHandler(item, handler);
}
var handler = EventSubscriber.AddEventHandler(eventInfo, timer, TimerElapsed);

EventSubscriber.RemoveEventHandler(eventInfo, timer, handler);