幽幽Net

导航

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

一、程序集(接口程序集):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\

注意:LyhInterface.dll不必随LyhClassLibrary1.dll, LyhClassLibrary2.dll,LyhClassLibrary3.dll发布到c:\libs\,其由主程序引用,随主程序发布并加载。

    public partial class Form1 : Form
    {
        List<LyhInterface.ILyhInterface> list = new List<LyhInterface.ILyhInterface>();
        int idx = 0;
        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[idx].Run();
                
            }
            catch(Exception ex)
            {
                idx++;
                MessageBox.Show(ex.Message);
            }
        }

 

posted on 2016-02-27 23:05  幽幽Net  阅读(5907)  评论(0编辑  收藏  举报