C# 动态加载程序集dll (实现接口)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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\
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 (实现接口)的主要内容,如果未能解决你的问题,请参考以下文章