gzsxy8013

导航

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

方法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()



Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=404051

posted on 2005-11-26 16:37  通晓  阅读(651)  评论(0编辑  收藏  举报