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

        /// <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

posted @ 2011-06-15 20:37  潇客的技术博客  阅读(1986)  评论(0编辑  收藏  举报