C# 反射调用C#DLL方法

发布时间 2023-09-14 14:45:26作者: 博客YS

 

  /// <summary>
        /// 反射调用程序集方法
        /// </summary>
        public void GetAssembly(string dllPath)
        {
            //加载程序集(dll文件地址),使用Assembly类 
            //"D:\\VSXM\\VS2022\\AirTightness\\AirTightness.Common\\bin\\Debug\\AirTightness.Common.dll"
            Assembly testDll = Assembly.LoadFile(dllPath);
            Type testClass = testDll.GetType("AirTightness.Common.CommonHelper");
            //创建实例
            object instance = testDll.CreateInstance("AirTightness.Common.CommonHelper");
            //获取方法(GetStr为方法名)
            MethodInfo methodGetStr = testClass.GetMethod("GetStr");
            //调用
            object result = methodGetStr.Invoke(instance, new object[] { "123" });
            MessageBox.Show(result.ToString());

            ////获取类型,参数(名称空间+类)
            //Type testClass = testDll.GetType("TestDLL.TestClass");
            ////创建实例
            //var instance = testDll.CreateInstance("TestDLL.TestClass");
            ////调用无参构造函数
            //ConstructorInfo noParamConstructor = testClass.GetConstructor(Type.EmptyTypes);
            //object testClassObject = noParamConstructor.Invoke(new object[] { });

            ////调用有参构造函数
            //ConstructorInfo paramConstructor = testClass.GetConstructor(new Type[] { Type.GetType("System.Int32") });
            //object testClassObject2 = paramConstructor.Invoke(new object[] { 2 });

            //#region 调用非静态方法
            //MethodInfo addMethod = testClass.GetMethod("Add");
            //object addValue = addMethod.Invoke(instance, new object[] { });
            //#endregion

            //#region 调用静态有参方法
            //MethodInfo sayHiMethod = testClass.GetMethod("SayHi");
            //object sayHi = sayHiMethod.Invoke(null, new object[] { "jason" });
            //#endregion

            //#region 调用含有ref参数的方法
            //MethodInfo exchange = testClass.GetMethod("Exchange");
            //var objs = new object[2];
            //objs[0] = 5;
            //objs[1] = 6;
            //Console.WriteLine("objs[0]={0}\nobjs[1]={1}", objs[0], objs[1]);
            //object retValue = exchange.Invoke(instance, objs);
            //#endregion

            //#region 调用参数为数组的方法
            //MethodInfo addValueInfo = testClass.GetMethod("AddValue");
            //var ints = new int[] { 1, 2, 3, 4, 5 };
            //object obj = addValueInfo.Invoke(null, new object[] { ints });
            //#endregion
        }