使用反射实现根据名称动态创建窗体的几种方法。

‘ 方法 1 使用 activator 方法创建实例

Dim str As String

str = "Form2" ' 必须是 命名空间 + 点 + 窗体类名(这里假设为命名空间为空)

Dim tempAssembly As [Assembly] = [Assembly].GetExecutingAssembly()

Dim t As Type = tempAssembly.GetType(str)

Dim args() As Object = Nothing

Dim o As Object = System.Activator.CreateInstance(t, args)

CType (o, Form2).Show()

'Dim frm2 As Form = CType(tempAssembly.CreateInstance(str), Form)

'frm2.Show()

‘ //////////////// 方法 2 使用构造函数的 invoke 方法创建实例。

Dim ty() As Type = {} ‘ 该构造函数没有参数

Dim c As ConstructorInfo = t.GetConstructor(ty) ‘ 获得没有参数的构造函数

Dim args1() As Object = Nothing ‘参数为空

Dim p As Object = c.Invoke( Nothing ) ‘创建实例时参数为空

CType (p, Form2).Show()

‘ 方法 3 ‘ /////////////////////////////////////// 使用 assembly.createinstance 方法创建实例

Dim str As String

str = "Form2" ' 必须是 命名空间 + 点 + 窗体类名

Dim tempAssembly As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()

Dim frm2 As Form = CType (tempAssembly.CreateInstance(str), Form)

frm2.Show()

Published At
Categories with Web编程
Tagged with
comments powered by Disqus