枚举 VB.NET 项目中的所有表单,然后按名称或全名显示?

Enumerate all forms in VB.NET project, then show them by Name or Fullname?

如何创建对表单的引用,仅通过其名称或.Fullname..?看起来很简单,但是我试过都不行。

鉴于以下代码,最后的部分是我卡住的地方。

谢谢。

Public Class frmLauncher

Private Sub FormPicker_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim myAssembly As System.Reflection.Assembly =  System.Reflection.Assembly.GetExecutingAssembly()
    Dim myTypes() As Type = Nothing

    ' Both of the following lines seem to do the same thing.
    ' Is one way better or safer than the other? 
    myTypes = myAssembly.DefinedTypes
    myTypes = myAssembly.GetTypes

    For Each t In myTypes
        If t.BaseType.FullName.ToString.ToUpper = "System.Windows.Forms.Form".ToUpper Then
            ListBox1.Items.Add(t.Name)
        End If
    Next

End Sub

Private Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick

    Dim frmName As String = ListBox1.Text

    ' the next line is where I'm totally stuck.
    Dim frm As Form = GetSomethingUnknown(frmName)  

    frm.Show()

End Sub

End Class

要创建您的表单实例,首先将全名 属性 添加到您的列表框中,这还包括您自己的应用程序的名称空间,并且需要通过反射找到表单 类

For Each t In myTypes
    If t.BaseType.FullName.ToString.ToUpper = "System.Windows.Forms.Form".ToUpper Then
        ListBox1.Items.Add(t.FullName)
    End If
Next

现在创建实例所需的代码如下

Private Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick

    Dim frmName As String = ListBox1.Text

    Dim myAssembly As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()
    Dim obj = myAssembly.GetType(frmName).InvokeMember(Nothing, Reflection.BindingFlags.CreateInstance, Nothing, Nothing, Nothing)
    Dim frm As Form = CType(obj, System.Windows.Forms.Form)
    frm.Show()
End Sub

如您所见,这里的关键点是来自您的 frmName 变量标识的类型的 call to InvokeMember 方法。这是一个复杂的方法,如果您真的想使用反射代码,您应该仔细研究它。