One, assembly (interface assembly): LyhInterface.Dll
Namespace Lyhinterface
{
public interface Ilyhinterface
{
void Run ();
}
}
Two, assembly (the Assembly that implements the interface): LyhClassLibrary1.dll, Lyhclasslibrary2.dll,lyhclasslibrary3.dll, all assembly references: 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 ());
}
}
}
Iv. Main Program
1. Reference: LyhInterface.dll
2. Dynamic loading assembly: LyhClassLibrary1.dll, Lyhclasslibrary2.dll,lyhclasslibrary3.dll, storage folder: 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 # Dynamically loading assembly DLLs (implementing interfaces)