如何在对象的构造函数完成后立即触发事件? [英] How do I get an event to fire as soon as an object's constructor has finished?

查看:49
本文介绍了如何在对象的构造函数完成后立即触发事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

研究告诉我,从构造函数本身引发事件是不可行的,因为该对象可能未完全初始化...所以构造函数触发后,我可以在哪里触发事件?

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?

推荐答案

您可以做的一件事是添加一种方法来处理其他后继任务:

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

其他地方:

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调用子程序引发事件将无法与类一起使用的原因是:

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

关键是 Handles Foo.SomeEvent

尚无 Foo 可以处理该事件.它不会崩溃,不会引发事件,但是没有对象可以让侦听器捕获/处理该事件.在 InitializeComponents 中创建了足够的表单,它可以与表单一起使用.

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.

这篇关于如何在对象的构造函数完成后立即触发事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆