How are events implemented

前端 未结 2 1160
悲哀的现实
悲哀的现实 2021-01-25 14:13

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

2条回答
  •  时光说笑
    2021-01-25 14:52

    An event is just a delegate. Here's some code to play with that works just like a regular event, using a delegate object instead:

    Module Module1
        Sub Main()
            Dim obj As New Example
            obj.AnEvent = New EventHandler(AddressOf Handler)
            obj.Test()
            Console.ReadLine()
        End Sub
    
        Sub Handler(ByVal sender As Object, ByVal e As EventArgs)
            Console.WriteLine("got event")
        End Sub
    End Module
    
    Class Example
        Public AnEvent As EventHandler
        Public Sub Test()
            If AnEvent IsNot Nothing Then AnEvent(Me, EventArgs.Empty)
        End Sub
    End Class
    

    But do note the problem with this code. Some other code could mess with AnEvent as well. Like replacing it or setting it back to Nothing. That's disastrous in most any case, the code that subscribed the event first will stop working properly.

    The Event keyword in VB.NET prevents this from happening. It wraps the delegate object and makes it inaccessible to other code, beyond the provided keywords. Somewhat similar to how a Property protects access to a field. AddHandler and RemoveHandler ensure that existing registrations cannot disappear. RaiseEvent fires the event without the need for the Nothing check.

提交回复
热议问题