How do I get an event to fire as soon as an object's constructor has finished?

和自甴很熟 提交于 2021-02-09 12:15:10

问题


Research tells me that raising an event from the constructor itself is not feasible as the object may not be fully initialised... so where can I fire an event from as soon as the constructor has fired?


回答1:


One thing you can do is add a method to handle additional post ctor tasks:

Friend Class FooBar

     Public Sub New
         ' your code here
     End Sub

     Public Sub Create
        ' do anything you want
     End Sub

End Class

Elsewhere:

Friend WithEvents Foo As Foobar

' ...
Foo = New FooBar      '  Foo doesnt exist until ctor code executes and the
                      ' code returns to here. 

Foo.Create            ' do whatever you like, as long as any other
                      ' objects referenced have been created.               

The reason calling a sub from the ctor to raise an event wont work with a class is this:

Private Sub SomeEvent(sender As Object, e As EventArgs) Handles Foo.SomeEvent
    Console.Beep()
End Sub

the key is Handles Foo.SomeEvent

There is no Foo yet to handle the event. It doesnt crash and there event is raised, but there is no object for the listener to catch/handle the event. Enough of a form is created in InitializeComponents, that it does work with a form.

There might also be an Interface to implement something like this, I know of some for Components, but not classes.




回答2:


You could use the Load or Show events from the Shown.

   Private Sub myForm_Shown(sender As Object, e As EventArgs) Handles Me.Shown

   End Sub

or

 Private Sub myForm_Load(sender As Object, e As EventArgs) Handles Me.Load

    End Sub



回答3:


You can accomplish this by adding an Action(Of T) parameter to your constructor and invoke the delegate on the very last line.

Public Class Foo

    Public Sub New(ByVal action As Action(Of Foo))
        '...
        '...
        '...
        If (Not action Is Nothing) Then action.Invoke(Me)
    End Sub

End Class

Example

Public Class Form1

    Private Sub Button1_Click(sender As Object, ev As EventArgs) Handles Button1.Click
        Dim foo1 As New Foo("foo1", AddressOf Me.HandleFooCtor)
        Dim foo2 As New Foo("foo2", Sub(f As Foo) MessageBox.Show(f.Name))
    End Sub

    Private Sub HandleFooCtor(f As Foo)
        MessageBox.Show(f.Name)
    End Sub

    Public Class Foo

        Public Sub New(name As String, Optional ByVal action As Action(Of Foo) = Nothing)
            '...
            '...
            '...
            Me.Name = name
            If (Not action Is Nothing) Then action.Invoke(Me)
        End Sub

        Public ReadOnly Name As String

    End Class

End Class


来源:https://stackoverflow.com/questions/23552030/how-do-i-get-an-event-to-fire-as-soon-as-an-objects-constructor-has-finished

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!