C#_利用反射通过Appdomain调用静态类中的方法

直接上代码了:

我的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 方法。

posted @ 2020-03-31 14:58  自定义的星空  阅读(1738)  评论(0)    收藏  举报