vb.net auto instantiation (forms)

心不动则不痛 提交于 2019-12-02 10:23:42

问题


In VB.Net you can show a form without crete an object reference before... vb.net do it to you, but, that "feature" is generating many problems, eg:

Public Class Form1

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Form3.Show()
End Sub
End Class

Public Class Form3
    Inherits System.Windows.Forms.Form
End Class

Is there any way to disable this?


回答1:


No there is no way to disable that. It is called the default instance. If you don't want to use it - don't use it. I recommend creating a new instance.

Dim f3 As New Form3
f3.Show()



回答2:


I looking for a solution to do the same and ran across this thread.

Seeing that there is no way to get rid of the default instance, and it would allow you to make the "whoops" of calling the form without an object reference, I just resorted to do this:

''' <summary>
''' This overrided of Sub New is only here to force you to create an object reference. Passing true or false will make no difference.
''' </summary>
Public Sub New(MustInstanciate As Boolean)
    ' This call is required by the designer.
    InitializeComponent()
    ' Add any initialization after the InitializeComponent() call.
End Sub

This forces you to create an object reference because it gets rid of the implicit Sub New, having only one constructor which requires a variable, which requires an object reference.

This trick works for me at least. I just thought I would just add it as a solution in case someone else runs into this thread for the same reason I did.



来源:https://stackoverflow.com/questions/18000482/vb-net-auto-instantiation-forms

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