真正简单的处理方法是使用表单类型的默认实例。在 VB 中,自 2005 年以来,每种表单类型都有一个默认实例,您可以通过类型名称访问该实例。 Read here 了解更多信息。在你的情况下,你可以这样做:
'Display the form if it is not already displayed.
ExpenseEntry.Show()
'Activate the form if it is already displayed.
ExpenseEntry.Activate()
'Do the deed.
ExpenseEntry.OpenVouncher()
也就是说,默认实例有点狡猾。它们确实使初学者能够在某些情况下从项目中的任何地方访问表单,但它们也有可能导致问题的限制。但最重要的是,它们通过将表单与其他类型区别对待来帮助阻止您学习正确的 OOP。如果您想按照适当的开发人员的方式执行此操作,那么只需声明一个变量来引用表单的当前实例:
Private expenseEntryDialogue As ExpenseEntry
当需要使用表单时,您只需检查该变量是否引用了一个可用的实例,如果是则使用它,否则创建一个新实例:
If expenseEntryDialogue Is Nothing OrElse expenseEntryDialogue.IsDisposed Then
expenseEntryDialogue = New ExpenseEntry
End If
expenseEntryDialogue.Show()
expenseEntryDialogue.Activate()
expenseEntryDialogue.OpenVoucher()
第三种选择是实现您自己的单例,即只能有一个实例的类型。你可能不会在 VB 中这样做,因为默认实例基本上是一个特定于线程的单例,并且会更自动地执行,但如果你愿意,你可以这样做:
Public Class ExpenseEntry
Private Shared _instance As ExpenseEntry
'The one and only instance of the type.
Public Shared ReadOnly Property Instance As ExpenseEntry
Get
If _instance Is Nothing OrElse _instance.IsDisposed Then
_instance = New ExpenseEntry
End If
Return _instance
End Get
End Property
'The constructor is private to prevent external instantiation.
Private Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
End Sub
End Class
然后是这个:
ExpenseEntry.Instance.Show()
ExpenseEntry.Instance.Activate()
ExpenseEntry.Instance.OpenVoucher()