Use of multicast in C# multicast delegates

社会主义新天地 提交于 2019-11-28 08:34:46

问题


When is it useful to have multicast delegates over singlecast delegates?

I use delegates a lot, mainly coupled with C# lambdas, but I've never felt the urge to use the multicast aspect of C# delegates, ie I've never wanted to combine multiple delegates together in a single delegate. I'm therefore very curious in what sort of situation multicast delegates are useful - I can only think of examples in which you can easily implement the functionality some other way, by, say, chaining the delegates or putting them in a list.

In particular, Eric Lippert's answer here gives the impression even the C# team sometimes forgets about the multicastiness of delegates.


回答1:


Anything acting as an event is the classic answer here - then the caller doesn't need to know who is listening (just invoke it, if it is non-null). This is ideal as multiple operations can subscribe simultaneously - for example 3 separate controls observing (data-binding) to the same property on a view-model.

Any cases where the delegate is acting as function (in particular with a return value) is tricker, as you need to think how you will handle that - take the first? Last? Aggregate?




回答2:


Events are a prime example for the usage of MulticastDelegates. So, probably without realizing it, you are using them every day.



来源:https://stackoverflow.com/questions/6297550/use-of-multicast-in-c-sharp-multicast-delegates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!