事件与代表之间的差异及其各自的应用 [英] Difference between events and delegates and its respective applications

查看:84
本文介绍了事件与代表之间的差异及其各自的应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了使用语法糖,我看不到使用事件的优势。也许我有误会,但似乎事件只是代表的占位符。



你会向我解释差异,何时使用哪个?有哪些优点和缺点?我们的代码很大程度上取决于事件,我想要到底。

什么时候可以使用代理事件,反之亦然?请在生产代码中说明您的真实世界经验。

解决方案

从技术的角度来看,其他答案已经解决了差异



从语义的角度来看,事件是满足某些条件时由对象引发的动作。例如,我的股票类有一个名为Limit的属性,当股票价格达到Limit时,它会引发一个事件。此通知是通过事件完成的。是否有任何人真正关心这个事件并订阅它是超出所有者类的关注。



代理是一个更通用的术语来描述类似于指针的构造用C / C ++语言。 .Net中的所有代表都是多播代理。从语义的角度来看,它们通常被用作一种输入。特别是,它们是实现策略模式的完美方法。例如,如果我想对对象列表进行排序,我可以提供比较器策略来告诉实现如何比较两个对象。



我已经使用生产代码中的两种方法。某些属性满足时,我的数据对象的Tons会通知。最基本的例子,每当一个属性发生变化时,会引发一个PropertyChanged事件(参见INotifyPropertyChanged接口)。我已经在代码中使用代理来提供将某些对象转换成字符串的不同策略。这个特殊的例子是一个荣耀的ToString()列表,用于将特定对象类型的实现显示给用户。


I don't see advantages of using events over delegates, other than being syntactical sugar. Perhaps I am misunderstanding, but it seems that event is just a placeholder for delegate.

Would you explain to me the differences and when to use which? What are the advantages and disadvantages? Our code is heavily rooted with events, and I want to get to the bottom of it.

When would you use delegates over events and vice versa? Please state your real world experience with both, say in the production code.

解决方案

From the technical standpoint, other answers have addressed the differences.

From a semantics perspective, events are actions raised by an object when certain conditions are met. For example, my Stock class has a property called Limit, and it raises an event when the stock prices reaches the Limit. This notification is done via an event. Whether anyone actually cares about this event and subscribes to it is beyond the concern of the owner class.

A delegate is a more generic term to describe a construct similar to a pointer in C/C++ terms. All delegates in .Net are multicast delegates. From a semantics perspective, they are generally used as a kind of input. In particular, they are a perfect way to implement the Strategy Pattern. For example, if I want to sort a List of objects, I can provide a Comparator strategy to the method to tell the implementation how to compare two objects.

I have used the two methods in production code. Tons of my data objects notify when certain properties are met. Most basic example, whenever a property changes, a PropertyChanged event is raised (see INotifyPropertyChanged interface). I have used delegates in code to provide different strategies of turning certain objects into string. This particular example was a glorified ToString() list of implementations for a particular object type to display it to users.

这篇关于事件与代表之间的差异及其各自的应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆