示例:动态加载dll并调用其方法
DllLib.dll
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DllLib { public class Class1 { public static void Show1() { Console.WriteLine("Class1 static Show1"); } public void Show2() { Console.WriteLine("Class1 Show2"); } } public class Class2 { public static void Show1() { Console.WriteLine("Class2 static Show1"); } public void Show2() { Console.WriteLine("Class2 Show2"); } } }
测试类
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace AssemblyTest1 { class Program { static void Main(string[] args) { //加载程序集 Assembly assembly; byte[] rawAssembly = loadFile("DllLib.dll"); //如果调试文件存在 if (File.Exists("DllLib.pdb")) { byte[] rawSymbolStore = loadFile("DllLib.pdb"); assembly = Assembly.Load(rawAssembly, rawSymbolStore); } else { assembly = Assembly.Load(rawAssembly); } Type type1 = assembly.GetType("DllLib.Class1");//这里要填FullName //调用静态方法 MethodInfo mi = type1.GetMethod("Show1", BindingFlags.Static | BindingFlags.Public); mi.Invoke(null, null); //调用实例方法 mi = type1.GetMethod("Show2", BindingFlags.Instance | BindingFlags.Public); //创建实例的两种方式 //Activator.CreateInstance(type1) //assembly.CreateInstance("DllLib.Class1") mi.Invoke(Activator.CreateInstance(type1), null);//通常用这种方式创建实例对象 mi.Invoke(assembly.CreateInstance("DllLib.Class1"), null); Console.Read(); } static byte[] loadFile(string filename) { FileStream fs = new FileStream(filename, FileMode.Open); byte[] buffer = new byte[(int)fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); return buffer; } } }
运行测试