在 C# 多播委托中使用多播

Use of multicast in C# multicast delegates(在 C# 多播委托中使用多播)

本文介绍了在 C# 多播委托中使用多播的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

多播委托优于单播委托什么时候有用?

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

我经常使用委托,主要是与 C# lambdas 结合使用,但我从未有过使用 C# 委托的多播方面的冲动,即我从未想过将多个委托组合在一个委托中.因此,我很好奇多播委托在何种情况下有用 - 我只能想到一些示例,在这些示例中,您可以通过其他方式轻松实现该功能,例如链接委托或将它们放入列表中.

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.

特别是 Eric Lippert 的回答 这里 给人的印象是即使 C# 团队有时也会忘记代表的多播性.

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

推荐答案

任何充当事件的东西都是这里的经典答案 - 然后调用者不需要知道谁在听(只要调用它,如果它不是空值).这是理想的,因为多个操作可以同时订阅 - 例如 3 个单独的控件观察(数据绑定)到视图模型上的相同属性.

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?

这篇关于在 C# 多播委托中使用多播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 C# 多播委托中使用多播

基础教程推荐