C# 动态加载程序集dll (实现接口)
2016-02-27 23:05
639 查看
一、程序集(接口程序集):LyhInterface.Dll
二、程序集(实现接口的程序集):LyhClassLibrary1.dll, LyhClassLibrary2.dll,LyhClassLibrary3.dll,所有程序集引用:LyhInterface.dll
四、主程序
1、引用:LyhInterface.dll
2、动态加载程序集:LyhClassLibrary1.dll, LyhClassLibrary2.dll,LyhClassLibrary3.dll,存储文件夹:c:\libs\
注意:LyhInterface.dll不必随LyhClassLibrary1.dll, LyhClassLibrary2.dll,LyhClassLibrary3.dll发布到c:\libs\,其由主程序引用,随主程序发布并加载。
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); } }
相关文章推荐
- C#生成exe、dll版本号自动增加
- C# AD(Active Directory)域信息同步,组织单位、用户等信息查询
- C# 指南之装箱与拆箱
- C#综合揭秘——细说多线程(下)
- 2.C#中泛型在方法Method上的实现
- C#综合揭秘——细说多线程(上)
- 1.什么是泛型和C#中泛型在Class上的实现
- 七层登录——C#
- 订阅者方法超时的处理
- [hdu5632][BC#73 1002]Rikka with Array
- C# 枚举、字符串、值的相互转换
- C#学习语录
- C#虚基类继承与接口的区别
- C#_在VS2010下进行单元测试
- C# String与string的区别
- C# 中的委托和事件
- C# 索引器的使用
- C#套接字使用
- C#获取 URL参数
- C#判断