如题
下列代码可以实现由窗体名来创建这个窗体的实例,但如何用代码来获取命名空间名?
Dim str As String
str = "myTest.Form2" '必须是 命名空间+点+窗体类名
Dim tempAssembly As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()
Dim frm2 As Form = CType(tempAssembly.CreateInstance(str), Form)
frm2.Show()
---------------------------------------------------------------
1.如果只有一个根命名空间则可以采用下面的方式:
Dim str As String
Dim tempAssembly As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()
str = tempAssembly.GetName.Name & ".Form2" '(Assembly.GetName.Name就是默认的根命名空间)
Dim frm2 As Form = CType(tempAssembly.CreateInstance(str), Form)
frm2.Show()
2.如果存在二级及以上的命名空间,那就没办法了,如果在所有的tempAssembly下的命名空间中有不重名的窗体,则可以采用查询的方式:
Dim str As String
Dim tempAssembly As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()
dim otype as type
dim otypes as type = tempAssembly.Getypes()
dim i as integer
for i=0 to otypes.length-1
if Instr(otypes(i).Name,"Form2")>=0 then
otype = otypes(i)
exit for
end if
next
if not otype is noting then
str = otype.FullName()'获取带有命名空间的类名
Dim frm2 As Form = CType(tempAssembly.CreateInstance(str), Form)
frm2.Show()
end if