.vane

笑舞狂歌五十年,花中行乐月中眠
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

根据类名实例化一个对象(反射)

Posted on 2009-12-20 00:36  花白  阅读(1479)  评论(0)    收藏  举报

    最近在CSDN上看到一个06年的帖子,楼主提问如下:

    Q:在开发WinForm程序中需要这样一个函数:   
       输入一个Form的类名,在函数中判断该类是否存在,然后判断该类是否有实例存在,如存在则Show出来,如不存在则实例化一个,再Show出来。

    原帖地址:http://topic.csdn.net/t/20060414/18/4687803.html

    虽然回帖提到使用反射能解决这个问题,但最后貌似帖子无疾而终了,那我就顺着反射这个切入点继续把问题解决方案补充完整吧。

    MYAnswer:

 

通过反射判断程序中特定类名的窗体是否已打开,打开则显示,未打开则新建并打开
 1 Assembly tempAssembly = Assembly.GetExecutingAssembly();//反射得到包含当前运行代码所在程序集
 2 //通过反射得到欲查找窗体类的一个实例,"MPM_ManagementSystem.FormAbout"为欲查找的窗体类的全名
 3 Form frm = (Form)tempAssembly.CreateInstance("MPM_ManagementSystem.FormAbout"true);
 4 int index=-1;
 5 //遍历当前应用程序打开的窗体集合
 6 for (int i = 0; i < Application.OpenForms.Count; i++)
 7 {
 8      //判断当前打开的窗体中是否有与frm同名的,有则表示已打开MPM_ManagementSystem.FormAbout的一个窗体实例
 9      if (frm.Name==Application.OpenForms[i].Name)
10     {
11         index = i;//有则获取此窗体在当前窗体集合中的索引值 
12     }
13 }
14 if (index > 0)//已存在该窗体
15 {
16     frm.Dispose();//既然已经打开了,我就灭掉你,你的出生也许是个错误,哎。。。- -!
17     MessageBox.Show("已打开名为"+Application.OpenForms[index].Name+"的窗口","提示");
18     Application.OpenForms[index].Focus();//前端显示已打开的窗体
19 }
20 else
21 {
22     MessageBox.Show("将新建名为"+frm.Name+"的窗口""提示");
23     frm.Show();
24 }