简体   繁体   中英

C# Event invocation list filtering

I have one event in 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". 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,并在观察者的更新方法中实现您的逻辑。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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