直接上代码了:
我的DLL(class library):
namespace MyClassLibrary { public static class Test { [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern int MessageBox(IntPtr hWnd, string lpText, string lpCaption, uint uType); public static void Show() { Console.WriteLine("123"); } public static string ShowUpper(string str) { Console.WriteLine(str.ToUpper()); return str.ToUpper(); } } }
Code:
class Program { static void Main(string[] args) { var loadedAssembliesBefore = AppDomain.CurrentDomain.GetAssemblies(); var domain = AppDomain.CreateDomain("Domain"); domain.DoCallBack(LoadAssemblyAndCallStaticMethod); Console.ReadKey(); } static void LoadAssemblyAndCallStaticMethod() { var assembly = Assembly.LoadFrom(@"D:\TestFile\MyClassLibrary.dll"); //dll路径 Type t = assembly.GetType("MyClassLibrary.Test"); t.InvokeMember("Show", BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, new object[0] { }); } }
注意:反射只能针对托管代码,对于P/Invoke非托管代码不能使用,所以不能调用 MessageBox 方法。