使用反射完成根據(jù)名稱動(dòng)態(tài)創(chuàng)建窗體的幾種方法
發(fā)表時(shí)間:2024-02-15 來源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
[摘要]‘方法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()