简体   繁体   English

C#事件调用列表过滤

[英]C# Event invocation list filtering

I have one event in C#. 我在C#中有一个事件。 There are five subscribers for that. 有五个订阅者。 All the subscribers are different classes. 所有订阅者都是不同的类。 But while raising the event i want that not all the subscriber/handler should be notified to handle this event. 但在提升事件的同时,我希望不是所有的订阅者/处理者都应该被通知来处理这个事件。 I should have some filtering mechanism and then only remaining subscribers should be notified. 我应该有一些过滤机制,然后只应通知剩余的订阅者。 What could be the best way to achieve this? 有什么可能是实现这一目标的最佳方式?

If you want to do it with your existing even then just iterate through the invocation list on the event. 如果你想用你现有的东西做,那么只需迭代事件的调用列表。

var list = localHandler.GetInvocationList();
foreach (EventHandler<T> item in list)
{
    if(((ICanDoThing)item.Target).CanDoThing)
    {
        item(this, someArgs);
    }
 }

Now, you can see I've cast item.Target to a type of ICanDoThing, which is an interface I've just made up that exposes a method "CanDoThing". 现在,您可以看到我已经将item.Target转换为ICanDoThing类型,这是我刚刚编写的一个接口,它公开了一个方法“CanDoThing”。 This allows you to query the object for whether it supports your particular need. 这允许您查询对象是否支持您的特定需求。

You should probably question whether you should use an event anyway for this, but the above will allow you to do so. 您可能会质疑是否应该为此使用事件,但上述内容将允许您这样做。

I think you need multiple events here, so that subscribers can subscribe to the events they really want. 我认为你需要多个事件,以便订阅者可以订阅他们真正想要的事件。

Subscribing an event means that you are interested in an event. 订阅活动意味着您对活动感兴趣。 If you are not interested in an event you should not subscribe it. 如果您对某个活动不感兴趣,请不要订阅。

您可以使用观察者模式,如下所述: http//www.dofactory.com/Patterns/PatternObserver.aspx,并在观察者的更新方法中实现您的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM