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 = ;
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{ string dir = @"c:\Libs\";
string assemblyName = "LyhClassLibrary";
for (int i = ; i < ; i++)
{
Assembly assembly = Assembly.LoadFile(dir + assemblyName + (i+).ToString() + ".dll");
Type type = assembly.GetType(assemblyName + (i+).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#动态加载程序集(转)


下一篇:应用程序域 System.AppDomain,动态加载程序集