代表和活动之间有什么区别?
代表和活动之间有什么区别? 两者不都包含对可以执行的函数的引用吗?
What are the differences between delegates and an events? Don't both hold references to functions that can be executed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
用简单的方式定义事件:
事件是对委托的引用,有两个限制
以上两个是代表们的弱点,并在活动中得到解决。 显示 fiddler 差异的完整代码示例位于 https://dotnetfiddle.net/5iR3fB 。
切换事件和委托之间的注释以及调用/分配值给委托的客户端代码以了解差异
以下是内联代码。
To define about event in simple way:
Event is a REFERENCE to a delegate with two restrictions
Above two are the weak points for delegates and it is addressed in event. Complete code sample to show the difference in fiddler is here https://dotnetfiddle.net/5iR3fB .
Toggle the comment between Event and Delegate and client code that invokes/assign values to delegate to understand the difference
Here is the inline code.
.net 中的事件是 Add 方法和 Remove 方法的指定组合,这两种方法都需要某种特定类型的委托。 C# 和 vb.net 都可以自动生成添加和删除方法的代码,这些方法将定义一个委托来保存事件订阅,并向该订阅委托添加/删除传入的委托。 当且仅当订阅列表非空时,VB.net 还将自动生成代码(使用 RaiseEvent 语句)来调用订阅列表; 由于某种原因,C# 不会生成后者。
请注意,虽然使用多播委托管理事件订阅很常见,但这并不是唯一的方法。 从公共角度来看,潜在的事件订阅者需要知道如何让对象知道它想要接收事件,但不需要知道发布者将使用什么机制来引发事件。 另请注意,虽然在 .net 中定义事件数据结构的人显然认为应该有一种公共方法来引发它们,但 C# 和 vb.net 都没有使用该功能。
An event in .net is a designated combination of an Add method and a Remove method, both of which expect some particular type of delegate. Both C# and vb.net can auto-generate code for the add and remove methods which will define a delegate to hold the event subscriptions, and add/remove the passed in delegagte to/from that subscription delegate. VB.net will also auto-generate code (with the RaiseEvent statement) to invoke the subscription list if and only if it is non-empty; for some reason, C# doesn't generate the latter.
Note that while it is common to manage event subscriptions using a multicast delegate, that is not the only means of doing so. From a public perspective, a would-be event subscriber needs to know how to let an object know it wants to receive events, but it does not need to know what mechanism the publisher will use to raise the events. Note also that while whoever defined the event data structure in .net apparently thought there should be a public means of raising them, neither C# nor vb.net makes use of that feature.
您还可以在接口声明中使用事件,但对于委托则不然。
You can also use events in interface declarations, not so for delegates.
对于生活在 2020 年的人们来说,想要一个干净的答案...
定义:
delegate
:定义一个函数指针。事件
:定义+=
、-=
)、和new
关键字。关于形容词“受保护”:
另请注意 Microsoft 的此部分:https://learn.microsoft.com/en-us/dotnet/standard/events/#raise-multiple-events
代码示例:
使用
delegate
:with
event
:参考:
事件与委托 - 解释 C# 中事件和委托模式之间的重要区别以及它们为何有用。 >: https://dzone.com/articles/event-vs-delegate
For people live in 2020, and want a clean answer...
Definitions:
delegate
: defines a function pointer.event
: defines+=
,-=
), andnew
keyword anymore.Regarding the adjective protected:
Also notice this section from Microsoft: https://learn.microsoft.com/en-us/dotnet/standard/events/#raising-multiple-events
Code Example:
with
delegate
:with
event
:Reference:
Event vs. Delegate - Explaining the important differences between the Event and Delegate patterns in C# and why they're useful.: https://dzone.com/articles/event-vs-delegate
Delegate是一个类型安全的函数指针。 事件是使用委托的发布者-订阅者设计模式的实现。
Delegate is a type-safe function pointer. Event is an implementation of publisher-subscriber design pattern using delegate.
事件声明在委托实例上添加了一层抽象和保护。 此保护可防止委托的客户端重置委托及其调用列表,并且仅允许在调用列表中添加或删除目标。
An Event declaration adds a layer of abstraction and protection on the delegate instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list and only allows adding or removing targets from the invocation list.
要了解差异,您可以查看这 2 个
带有委托的示例示例(在本例中,是一个操作 - 这是一种不返回值的委托)
要使用委托,您应该执行如下操作:
此代码效果很好,但你可能有一些弱点。
例如,如果我这样写:
在最后一行代码中,我已经覆盖了之前的行为,只是缺少一个
+
(我使用了=
而不是+=
)另一个弱点是每个使用
Animal
类的类都可以直接调用委托。 例如,animal.Run()
或animal.Run.Invoke()
在 Animal 类之外有效。为了避免这些弱点,您可以在 C# 中使用
事件
。您的 Animal 类将以这种方式更改:
调用事件
差异:
animal.Run()
或animal.Run.Invoke()
在 Animal 类之外无效,并且会产生编译器错误。注意:
EventHandler 被声明为以下委托:
它采用发送者(对象类型)和事件参数。 如果发送者来自静态方法,则发送者为 null。
此示例使用
EventHandler
,也可以使用EventHandler
编写。有关 EventHandler 的文档,请参阅此处
To understand the differences you can look at this 2 examples
Example with Delegates (in this case, an Action - that is a kind of delegate that doesn't return a value)
To use the delegate, you should do something like this:
This code works well but you could have some weak spots.
For example, if I write this:
with the last line of code, I have overridden the previous behaviors just with one missing
+
(I have used=
instead of+=
)Another weak spot is that every class which uses your
Animal
class can invoke the delegate directly. For example,animal.Run()
oranimal.Run.Invoke()
are valid outside the Animal class.To avoid these weak spots you can use
events
in c#.Your Animal class will change in this way:
to call events
Differences:
animal.Run()
oranimal.Run.Invoke()
are invalid outside the Animal class and will produce compiler errors.Notes:
EventHandler is declared as the following delegate:
it takes a sender (of Object type) and event arguments. The sender is null if it comes from static methods.
This example, which uses
EventHandler<ArgsSpecial>
, can also be written usingEventHandler
instead.Refer here for documentation about EventHandler
除了语法和操作属性之外,还存在语义差异。
从概念上讲,委托是函数模板; 也就是说,它们表达了函数必须遵守的合同,才能被视为代表的“类型”。
事件代表……好吧,事件。 它们的目的是在发生事情时提醒某人,是的,它们遵循委托定义,但它们不是同一件事。
即使它们完全相同(在语法上和在 IL 代码中),仍然存在语义差异。 一般来说,我更喜欢为两个不同的概念使用两个不同的名称,即使它们以相同的方式实现(这并不意味着我喜欢两次使用相同的代码)。
In addition to the syntactic and operational properties, there's also a semantical difference.
Delegates are, conceptually, function templates; that is, they express a contract a function must adhere to in order to be considered of the "type" of the delegate.
Events represent ... well, events. They are intended to alert someone when something happens and yes, they adhere to a delegate definition but they're not the same thing.
Even if they were exactly the same thing (syntactically and in the IL code) there will still remain the semantical difference. In general I prefer to have two different names for two different concepts, even if they are implemented in the same way (which doesn't mean I like to have the same code twice).
这是另一个值得参考的好链接。
简而言之
,从文章中可以看出 - 事件是对委托的封装。
引用文章:
Here is another good link to refer to.
http://csharpindepth.com/Articles/Chapter2/Events.aspx
Briefly, the take away from the article - Events are encapsulation over delegates.
Quote from article:
活动与代表之间存在多大的误会!!! 委托指定类型(例如
类
或接口
),而事件只是一种成员(例如字段、属性等)。 而且,就像任何其他类型的成员一样,事件也有类型。 然而,在事件的情况下,事件的类型必须由委托指定。 例如,您不能声明接口定义的类型的事件。最后,我们可以做出以下观察:事件的类型必须由委托定义。 这是事件和委托之间的主要关系,在 ECMA-335 (CLI) 分区 I 到 VI:
但是,这一事实并不意味着事件使用支持委托字段。 事实上,事件可以使用您选择的任何不同数据结构类型的支持字段。 如果您在 C# 中显式实现事件,则可以自由选择存储事件处理程序的方式(请注意,事件处理程序是类型的实例。事件,而这又必须是委托类型——来自之前的观察)。 但是,您可以将这些事件处理程序(它们是委托实例)存储在诸如列表或字典或任何其他数据结构中,甚至存储在后备委托中场地。 但不要忘记,使用委托字段并不是强制性的。
What a great misunderstanding between events and delegates!!! A delegate specifies a TYPE (such as a
class
, or aninterface
does), whereas an event is just a kind of MEMBER (such as fields, properties, etc). And, just like any other kind of member an event also has a type. Yet, in the case of an event, the type of the event must be specified by a delegate. For instance, you CANNOT declare an event of a type defined by an interface.Concluding, we can make the following Observation: the type of an event MUST be defined by a delegate. This is the main relation between an event and a delegate and is described in the section II.18 Defining events of ECMA-335 (CLI) Partitions I to VI:
However, this fact does NOT imply that an event uses a backing delegate field. In truth, an event may use a backing field of any different data structure type of your choice. If you implement an event explicitly in C#, you are free to choose the way you store the event handlers (note that event handlers are instances of the type of the event, which in turn is mandatorily a delegate type---from the previous Observation). But, you can store those event handlers (which are delegate instances) in a data structure such as a
List
or aDictionary
or any other else, or even in a backing delegate field. But don’t forget that it is NOT mandatory that you use a delegate field.注意:如果您有权访问 C# 5.0 Unleashed,请阅读“限制标题为“事件”的第 18 章中的“委托的简单使用”,以更好地理解两者之间的差异。
举一个简单、具体的例子总是对我有帮助。 这是社区的一个。 首先,我将展示如何单独使用委托来完成事件为我们所做的事情。 然后我展示了相同的解决方案如何与
EventHandler
实例一起使用。 然后我解释为什么我们不想做我在第一个例子中解释的事情。 这篇文章的灵感来自 John Skeet 的一篇文章。示例 1:使用公共委托
假设我有一个带有单个下拉框的 WinForms 应用程序。 该下拉列表绑定到
List
。 其中 Person 具有 Id、Name、NickName、HairColor 属性。 主窗体上有一个自定义用户控件,用于显示该人的属性。 当某人在下拉列表中选择一个人时,用户控件中的标签会更新以显示所选人员的属性。以下是其工作原理。 我们有三个文件可以帮助我们将其组合在一起:
以下是每个类的相关代码:
这里是我们的用户控件:
最后,我们的 Form1.cs 中有以下代码。 这里我们调用 OnPersonChanged,它调用订阅委托的任何代码。
好的。 这就是您如何在不使用事件而仅使用委托的情况下实现此功能。 我们只是将一个公共委托放入一个类中——您可以将其设为静态或单例,或其他任何形式。 伟大的。
但是,但是,但是,我们不想做我上面描述的事情。 因为由于很多很多原因,公共字段不好。 那么我们有什么选择呢? 正如 John Skeet 所描述的,这里是我们的选择:
PersonChangedDel = null
,从而消除所有其他订阅另一个问题。 剩下的问题是,由于用户有权访问委托,因此他们可以调用调用列表中的目标——我们不希望外部用户有权访问何时引发我们的事件这里 第三个选项本质上是事件为我们提供的。当我们声明 EventHandler 时,它使我们能够访问委托——不是公开的,不是作为属性,而是我们将其称为仅具有添加/删除访问器的事件
。看看同一个程序是什么样子,但现在使用事件而不是公共委托(我还将我们的中介器更改为单例):
示例 2:使用 EventHandler 而不是公共委托
中介器:
请注意,如果您按 F12 键, EventHandler,它将向您显示定义只是一个带有额外“发送者”对象的通用化委托:
用户控件:
最后,这里是 Form1.cs 代码:
因为 EventHandler 需要 EventArgs 作为参数,所以我创建了这个类其中只有一个属性:
希望这能让您了解为什么我们有事件以及它们作为委托有何不同(但功能相同)。
NOTE: If you have access to C# 5.0 Unleashed, read the "Limitations on Plain Use of Delegates" in Chapter 18 titled "Events" to understand better the differences between the two.
It always helps me to have a simple, concrete example. So here's one for the community. First I show how you can use delegates alone to do what Events do for us. Then I show how the same solution would work with an instance of
EventHandler
. And then I explain why we DON'T want to do what I explain in the first example. This post was inspired by an article by John Skeet.Example 1: Using public delegate
Suppose I have a WinForms app with a single drop-down box. The drop-down is bound to an
List<Person>
. Where Person has properties of Id, Name, NickName, HairColor. On the main form is a custom user control that shows the properties of that person. When someone selects a person in the drop-down the labels in the user control update to show the properties of the person selected.Here is how that works. We have three files that help us put this together:
Here is the relevant code for each of the classes:
Here is our user control:
Finally we have the following code in our Form1.cs. Here we are Calling OnPersonChanged, which calls any code subscribed to the delegate.
Ok. So that's how you would get this working without using events and just using delegates. We just put a public delegate into a class -- you can make it static or a singleton, or whatever. Great.
BUT, BUT, BUT, we do not want to do what I just described above. Because public fields are bad for many, many reason. So what are our options? As John Skeet describes, here are our options:
PersonChangedDel = null
, wiping out all of the other subscriptions. The other problem that remains here is that since the users have access to the delegate, they can invoke the targets in the invocation list -- we don't want external users having access to when to raise our events.This third option is essentially what an event gives us. When we declare an EventHandler, it gives us access to a delegate -- not publicly, not as a property, but as this thing we call an event that has just add/remove accessors.
Let's see what the same program looks like, but now using an Event instead of the public delegate (I've also changed our Mediator to a singleton):
Example 2: With EventHandler instead of a public delegate
Mediator:
Notice that if you F12 on the EventHandler, it will show you the definition is just a generic-ified delegate with the extra "sender" object:
The User Control:
Finally, here's the Form1.cs code:
Because the EventHandler wants and EventArgs as a parameter, I created this class with just a single property in it:
Hopefully that shows you a bit about why we have events and how they are different -- but functionally the same -- as delegates.