码迷,mamicode.com
首页 > Windows程序 > 详细

C# 动态加载程序集dll (实现接口)

时间:2016-02-27 23:32:04      阅读:596      评论:0      收藏:0      [点我收藏+]

标签:

一、程序集(接口程序集):LyhInterface.Dll

namespace LyhInterface
{
    public interface ILyhInterface
    {
        void Run();
    }
}

 

二、程序集(实现接口的程序集):LyhClassLibrary1.dll, LyhClassLibrary2.dll,LyhClassLibrary3.dll,所有程序集引用:LyhInterface.dll   

namespace LyhClassLibrary1
{
    public class LyhClass : LyhInterface.ILyhInterface
    {
        public void Run()
        {
            throw new Exception(this.GetType().ToString());
        }
    }
}

 

namespace LyhClassLibrary2
{
    public class LyhClass : LyhInterface.ILyhInterface
    {
        public void Run()
        {
            throw new Exception(this.GetType().ToString());
        }
    }
}

 

namespace LyhClassLibrary3
{
    public class LyhClass : LyhInterface.ILyhInterface
    {
        public void Run()
        {
            throw new Exception(this.GetType().ToString());
        }
    }
}

 

四、主程序

1、引用:LyhInterface.dll   

2、动态加载程序集:LyhClassLibrary1.dll, LyhClassLibrary2.dll,LyhClassLibrary3.dll,存储文件夹:c:\libs\

    public partial class Form1 : Form
    {
        List<LyhInterface.ILyhInterface> list = new List<LyhInterface.ILyhInterface>();
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            string dir = @"c:\Libs\";
            string assemblyName = "LyhClassLibrary";
            for (int i = 0; i < 3; i++)
            {
                Assembly assembly = Assembly.LoadFile(dir + assemblyName + (i+1).ToString() + ".dll");
                Type type = assembly.GetType(assemblyName + (i+1).ToString() + ".LyhClass");
                LyhInterface.ILyhInterface instance = System.Activator.CreateInstance(type) as LyhInterface.ILyhInterface;
                list.Add(instance);
            }

        }

        private void button2_Click(object sender, EventArgs e)  

   {

      Try { list[0].Run(); }

      Catch(Exception ex) {MessageBox.Show(ex.Message); }

   }

 

        private void button3_Click(object sender, EventArgs e)  

   {

      Try { list[1].Run(); }

      Catch(Exception ex) {MessageBox.Show(ex.Message); }

   }

 

        private void button4_Click(object sender, EventArgs e)  

   {

      Try { list[2].Run(); }

      Catch(Exception ex) {MessageBox.Show(ex.Message); }

   }

C# 动态加载程序集dll (实现接口)

标签:

原文地址:http://www.cnblogs.com/cztaxlyh/p/5223820.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!