明輝手游網(wǎng)中心:是一個(gè)免費(fèi)提供流行視頻軟件教程、在線學(xué)習(xí)分享的學(xué)習(xí)平臺(tái)!

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

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

Dim str As String

        str = "Form2"  '必須是 命名空間+點(diǎn)+窗體類名(這里假設(shè)為命名空間為空)

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

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

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

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

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

        CType(p, Form2).Show()

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

      Dim str As String

        str = "Form2"  '必須是 命名空間+點(diǎn)+窗體類名

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

 

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

        frm2.Show()