事件如何实现 [英] How are events implemented
问题描述
我正在专门询问VB.NET,但我想像其他语言的一般原则是一样的。我认为一个事件是.NET中的一流概念,但是从反思看来,它只是一个
- 如何执行
AddHandler
和RemoveHandler
动态修改方法(AFAIK,事件预先DynamicMethod
-
RaiseEvent
如何调用方法? - 为什么
AddHandler
,RemoveHandler
和RaiseEvent
实现为语句而不是方法?
只是两种或三种方法的组合(加注部分是可选的),方式与属性是一种或两种方法的组合相同。
AddHandler
和 RemoveHandler
根本不修改方法,只需调用add和remo事件的ve部分,它们对于实现部分是可以重复的。
通常,通过对具有适当委托类型的字段的引用来实现事件,其中 Delegate.Combine
和 Delegate.Remove
用于执行相应的操作。 (字段值将被更改 - 请记住,代理类型是不可变的)。提出一个事件只是调用委托。
至于为什么 AddHandler
等是独立的语句类型 - 如果它们是方法,参数是什么?某事必须参考事件。基本上,一个 AddHandler
语句对应于适当的事件add方法,就像属性提取对应于适当的属性get方法一样。您可以通过 > EventInfo.AddHandler
。
查看我的关于代表和事件的文章可能有所帮助的更多细节 - 它来自C#背景,但原则显然是一样的。 >
I'm asking specifically about VB.NET, but I imagine the general principles are the same in other languages. I thought an event was a first-class concept in .NET, but it seems from reflection that its just a specific method which is called when the event is raised.
- How do
AddHandler
andRemoveHandler
modify the method dynamically (AFAIK, events pre-dateDynamicMethod
s? - How does
RaiseEvent
call the method? - Why are
AddHandler
,RemoveHandler
, andRaiseEvent
implemented as statements instead of methods?
No, an event is just a combination of two or three methods (the "raise" part is optional) in the same way that a property is a combination of one or two methods.
AddHandler
and RemoveHandler
don't modify methods at all. They just call the "add" and "remove" parts of the event, which are resposible for the implementation part.
Typically an event is implemented via a reference to a field with the appropriate delegate type, with Delegate.Combine
and Delegate.Remove
used to perform the appropriate operations. (The field value will be changed - bear in mind that delegate types are immutable.) Raising an event just consists of invoking the delegate.
As for why AddHandler
etc are separate statement types - if they were methods, what would the parameters be? Something has to refer to "the event". Basically an AddHandler
statement corresponds to the appropriate event "add" method, just as a property fetch corresponds to the appropriate property "get" method. You can do this with reflection, via EventInfo.AddHandler
.
See my article on delegates and events for more details which may help - it's from a C# background, but the principles are obviously the same.
这篇关于事件如何实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!