反射(三)利用反射部分更新UI界面

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();


            /* Example 3 UI*/
            Type[] typePublic = null; Type typeIExecute = null;
            string exeDirPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); //得到运行目录           


            string[] dellPaths = Directory.GetFiles(exeDirPath, "*.dll");//得到所有的DLL
            for (int i = 0; i < dellPaths.Length; i++)
            {
                Assembly asm = Assembly.LoadFile(dellPaths[i]);
                //Assembly asm = Assembly.LoadFrom("ClassLibrary1.dll");   
                typePublic = asm.GetExportedTypes();//得到所有的public方法  
                typeIExecute = typeof(IExecute);//接口的类型  


                for (int j = 0; j < typePublic.Length; j++)
                {
                    if (typeIExecute.IsAssignableFrom(typePublic[j]) && !typePublic[j].IsAbstract)//实现了IExecute,且非抽象类  
                    {
                        IExecute execut = (IExecute)Activator.CreateInstance(typePublic[j]);
                        ToolStripItem tsoitem = menuStrip1.Items.Add(execut.ExeName);//增加到菜单  
                        tsoitem.Click += new EventHandler(tsoitem_Click);//添加点击事件  
                        tsoitem.Tag = execut;//将namespace.class记录在新增控件的tag属性中  
                    }
                }
            }  
        }


        void tsoitem_Click(object sender, EventArgs e)
        {
            IExecute execut = (IExecute)((ToolStripItem)sender).Tag;


            execut.Execute();
        }  

    }


 public interface IExecute  
    {  
         
        string ExeName  
        {  
            get;  
            set;  
        }  
  
        ///<summary>  
        ///执行的方法  
        ///</summary>  
        void Execute();  
    }  

 public class One:IExecute
    {
        public One()
        {
            ExeName = "MenuOne";
        }
        public string ExeName
        {
            get;
            set;
        }


        public void Execute()
        {
            MessageBox.Show("Execute One");
        }  
    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值