‘方法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()
博客介绍了三种在编程中创建实例的方法。方法1使用activator方法,方法2使用构造函数的invoke方法,方法3使用assembly.createinstance方法,每种方法都给出了具体的代码示例,涉及Assembly、Type、Object等相关操作。
3540

被折叠的 条评论
为什么被折叠?



