2013/03/04

[C#] Dynamically load assembly (dll)

using System.Reflection;
using IterfaceLibrary;
 
IModuleInfo clientForm = null;
Form clientForm2 = null;
string formID = String.Empty;
Assembly newDll = Assembly.LoadFrom("Test.dll");
 
foreach (Type itemType in newDll.GetTypes())
{
  if (itemType.IsClass)
  {
    if (itemType.FullName.Contains("Form"))
    {
      // Assembly有implement Interface
      clientForm = Activator.CreateInstance(itemType) as IModuleInfo;
      MessageBox.Show(clientForm.ModuleName);
      clientForm.ShowForm(this, "From Main");

      // Assembly沒有implement Interface
      clientForm2 = Activator.CreateInstance(itemType) as Form;
      // 呼叫clientForm2裡面的ShowModuleID()方法,該方法回傳formID字串
      formID = itemType.InvokeMember("ShowModuleID", BindingFlags.InvokeMethod, null,
        clientForm2, null) as string;
      MessageBox.Show(formID);
    }
  }
}

No comments:

Post a Comment