Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm working on becoming as familiar with C# as I am with VB.NET (the language used at my workplace). One of the best things about the learning process is that by learning about the other language you tend to learn more about your primary language--little questions like this pop up:

According to the sources I've found, and past experience, a field in VB.NET that is declared as WithEvents is capable of raising events. I understand that C# doesn't have a direct equivalent--but my question is: fields without this keyword in VB.NET cannot raise events, is there a way to create this same behavior in C#? Does the VB compiler simply block these objects from having their events handled (while actually allowing them to raise events as usual)?

I'm just curious; I don't have any particular application for the question...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
457 views
Welcome To Ask or Share your Answers For Others

1 Answer

Omitting WithEvents doesn't block members from raising events. It just stops you from using the 'handles' keyword on their events.

Here is a typical use of WithEvents:

Class C1
    Public WithEvents ev As New EventThrower()
    Public Sub catcher() Handles ev.event
        Debug.print("Event")
    End Sub
End Class

Here is a class which doesn't use WithEvents and is approximately equivalent. It demonstrates why WithEvents is quite useful:

Class C2
    Private _ev As EventThrower
    Public Property ev() As EventThrower

        Get
            Return _ev
        End Get

        Set(ByVal value As EventThrower)
            If _ev IsNot Nothing Then
                    removehandler _ev.event, addressof catcher
            End If
            _ev = value
            If _ev IsNot Nothing Then
                    addhandler _ev.event, addressof catcher
            End If
        End Set
    End Property

    Public Sub New()
        ev = New EventThrower()
    End Sub

    Public Sub catcher()
        Debug.print("Event")
    End Sub
End Class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...