如何事件实现事件

2023-09-06 15:50:32 作者:感情路难走

我要问具体有关VB.NET,但我想一般的原则是在其他语言中的相同。我以为一个事件是.NET一流的概念,但它似乎从反射的,它只是一个的具体方法的时候,事件引发时调用。

如何的AddHandler RemoveHandler 修改方法的动态的(AFAIK,事件pre-日期 DynamicMethod的 S' 如何的RaiseEvent 调用的方法? 为什么的AddHandler RemoveHandler 的RaiseEvent 实现的语句的而不是方法的? 解决方案

没有,一个事件是两个或三个方法(以下简称募集部分是可选的)以同样的方式只是一个组合,一个属性是组合一种或两种方法。

的AddHandler RemoveHandler 不要修改方法的。他们只需要调用添加和删除部分的活动,这是resposible为实现部分。

典型的事件是通过引用场与适当的委托类型来实现,用的 Delegate.Combine 和的 Delegate.Remove 用于执行相应的操作。 (该字段值将被改变 - 记住,委托类型是不可改变的)。引发事件只是由调用委托

至于为什么的AddHandler 等都是独立的语句类型 - 如果他们的方法,将这些参数是什么?有些事情是指事件。基本上是一个的AddHandler 语句对应着相应的事件增加的方法,就像一个属性获取对应于相应的属性得的方法。您的可以的做到这一点与反思,通过的 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 and RemoveHandler modify the method dynamically (AFAIK, events pre-date DynamicMethods? How does RaiseEvent call the method? Why are AddHandler, RemoveHandler, and RaiseEvent 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.