开发者

VB.NET - problem with member's event handling

I discovered that an event raised (directly on indirectly) in the constructor cannot be handled outside the very class. To prove if that was the actual problem, I wrote a simple exemplary app.

Class with the event:

Namespace Utils
    Public Class A
        Public Eve开发者_开发问答nt Test()

        Public Sub New()
            CallTest()
        End Sub

        Public Sub MakeACall()
            CallTest()
        End Sub

        Private Sub CallTest()
            RaiseEvent Test()
        End Sub
    End Class
End Namespace

Main form (handling event properly):

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click

        m_A.MakeACall()
    End Sub

    Private Sub HandleTest() Handles m_A.Test
        MsgBox("ta-dah!")
    End Sub

    Protected WithEvents m_A As New Utils.A()
End Class

Main form (NOT handling event properly):

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click

        m_A = New Utils.A()
    End Sub

    Private Sub HandleTest() Handles m_A.Test
        MsgBox("ta-dah!")
    End Sub

    Protected WithEvents m_A As Utils.A
End Class

The reason of such behavior became quite obvious after writing those pieces, but maybe there is a way to omit it?


This is an acceptable pattern for handling this type of situation:

  1. Implement ISupportInitialize
  2. Fire your events in your EndInit method
  3. Throw an InvalidOperationException if someone tries to use your class without initializing it

This is a pretty universal way of dealing with situations like this, plus serializers respect the interface as well.


I would be surprised if this was an "issue" limited to Visual Basic; the fact is, the event can't be raised from an object that hasn't yet been created. As long as you're inside the constructor, creation hasn't finished. At least, that would make sense to me, and would seem to hold true regardless of language.

Different compilers may disagree.

However, the fact that all forms raise events the same way (Init, Loading, etc.) is fairly indicative that this is pretty close to the truth. Will's answer provides a great solution to your problem--which, when it gets down to it, isn't a problem at all: it's just the way objects work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜