简体   繁体   中英

MultiCast delegates in c#

When we use multicast delegates only the last method value is returned. Do we have any practical scenarios where all the methods need to be executed but only the last method value should be returned like what the multicast delegate does.

And Is there any relationship between events and multicast delegates?If yes, How are they linked?

Thankyou.

Is there any relationship between events and multicast delegates?

In C# every delegate declaration will generate a multicast delegate. And events are actually two methods internally, called add and remove accessors with a delegate parameter. They meant to add/remove subscribers (practically change an underlying multicast delegate instance).

Do we have any practical scenarios where all the methods need to be executed but only the last method value should be returned like what the multicast delegate does?

No, this should be actually avoided. That's why there aren't not non-void events in the framework. When using public events we can assume that they have more than one subscribers.

I will not repeat an earlier answer of mine for a similar question (how to return the result of every subscriber) but it also may worth checking: How to use string delegate subscribed to 2 methods

On the other hand, when delegate instances are just used as callbacks (eg. method parameters) they are often non-void ones (such as the Func<...> delegate family). Though technically they are also multicast delegates it is not expected that they have multiple targets. These are often instantiated by some lambda expression ( () => DoSomething() ) in which case they always have only a single target.

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