研究告诉我,从构造函数本身引发事件是不可行的,因为对象可能没有完全初始化...所以我可以在构造函数触发后立即从哪里触发事件?
答案 0 :(得分:1)
您可以使用显示的加载或显示事件。
Private Sub myForm_Shown(sender As Object, e As EventArgs) Handles Me.Shown
End Sub
或
Private Sub myForm_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
答案 1 :(得分:1)
您可以做的一件事是添加一个方法来处理其他后期任务:
Friend Class FooBar
Public Sub New
' your code here
End Sub
Public Sub Create
' do anything you want
End Sub
End Class
其他地方:
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.
调用来自ctor的sub来引发一个不能使用类的事件的原因是:
Private Sub SomeEvent(sender As Object, e As EventArgs) Handles Foo.SomeEvent
Console.Beep()
End Sub
密钥为Handles Foo.SomeEvent
尚未处理此事件的Foo
。它没有崩溃并且引发了事件,但是侦听器没有捕获/处理事件的对象。在InitializeComponents
中创建了足够的表单,它可以使用表单。
可能还有一个接口来实现这样的东西,我知道一些用于组件,但不是类。
答案 2 :(得分:0)
您可以通过向构造函数添加Action(Of T)参数并在最后一行调用委托来完成此操作。
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
示例强>
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