明輝手游網(wǎng)中心:是一個免費提供流行視頻軟件教程、在線學習分享的學習平臺!

使用反射完成根據(jù)名稱動態(tài)創(chuàng)建窗體的幾種方法

[摘要]‘方法1使用activator方法創(chuàng)建實例 Dim str As String str = "Form2" '必須是 命名空間+點+窗體類名(這里假設為命名空間為空) Dim tempAssembly As [Assembly] = [...
 方法1使用activator方法創(chuàng)建實例

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使用構造函數(shù)的invoke方法創(chuàng)建實例。

        Dim ty() As Type = {} 該構造函數(shù)沒有參數(shù)

        Dim c As ConstructorInfo = t.GetConstructor(ty) 獲得沒有參數(shù)的構造函數(shù)

        Dim args1() As Object = Nothing ‘參數(shù)為空

        Dim p As Object = c.Invoke(Nothing) ‘創(chuàng)建實例時參數(shù)為空

        CType(p, Form2).Show()

方法3 ///////////////////////////////////////使用assembly.createinstance方法創(chuàng)建實例

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