利用反射动态实例化类执行方法并传值

时间:2022-01-07 05:18:38

        /// <summary>
        /// 利用反射动态实例化类执行方法并传值
        /// </summary>
        /// <param name="className">类名</param>
        /// <param name="methodName">方法名</param>
        /// <param name="objParas">参数</param>
        /// <returns></returns>
        public static object GetMethod(string className,string methodName,object[] objParas)
        {
            Type t = Type.GetType(className);
            /*实例化这个类*/
            ConstructorInfo constructor = t.GetConstructor(new Type[0]);//将得到的类型传给一个新建的构造器类型变量
            object obj = constructor.Invoke(new object[0]);//使用构造器对象来创建对象
            /*执行Insert方法*/
            MethodInfo m = t.GetMethod(methodName);
            return m.Invoke(obj, objParas);
        }
        #endregion

 #region 反射实例化类里所有的成员
        public IMSDB()
        {
            var type = this.GetType();
            //反射解析 获取成员列表
            System.Reflection.PropertyInfo[] properties = type.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
            if (properties.Length > 0)
            {
                foreach (var pi in properties)
                {
                    var instance = Activator.CreateInstance(pi.PropertyType);
                    pi.SetValue(this, instance, null);
                }
            }
        }
#endregion