标签:
一、程序集(接口程序集):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); }
}
标签:
原文地址:http://www.cnblogs.com/cztaxlyh/p/5223820.html