通过反射找到并执行方法

需求是通过传入方法的名字,执行该方法,所有的方法都是传入一个model参数,但model的类型不一样。

通过上网查资料,整理了一下,具体代码如下:

      /// <summary>
        /// 执行方法(方法类型需要是公共的)
        /// </summary>
        /// <returns></returns>
        public ActionResult ExecutionMethod()
        {
            try
            {
                
                #region 通过反射找到方法所属的类并传入相应的model执行该方法

                // 1.执行方法的类 Load(命名空间名称),GetType(命名空间.类名) 
                Type type = Assembly.Load("命名空间名称").GetType("命名空间名称.类名");
                // 1.执行方法所需要的model Load(命名空间名称),GetType(命名空间.类名)
dynamic model = Assembly.Load("命名空间名称").GetType("命名空间名称.类名"); // 2.GetMethod(需要调用的方法名称) MethodInfo method = type.GetMethod("方法名"); // 3.调用的实例化方法(非静态方法)需要创建类型的一个实例 object obj = Activator.CreateInstance(type); // 3.实例化model dynamic models = Activator.CreateInstance(model); // 4.方法需要传入的参数,从Session获取到的参数反序列化为键值对类型 Dictionary<string, object> dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(Session["modelData"].ToString()); // 遍历传入的参数键值对,并赋值给实例化的model类 foreach (var item in dic) { PropertyInfo _Property = models.GetType().GetProperty(item.Key); if (_Property != null && _Property.CanRead) { //object的数值类型为Int64需要强制转换为Int32 if (item.Value.GetType().ToString() == "System.Int64") { _Property.SetValue(models, Convert.ToInt32(item.Value), null); } else { //给实例化的model赋值 _Property.SetValue(models, item.Value, null); } } }
// 执行查询方法所需要传入的参数 object[] parameters = new object[] { models };

          // 5.调用方法,如果调用的是一个静态方法,就不需要第3步(创建类型的实例) // 相应地调用静态方法时,Invoke的第一个参数为null object result = method.Invoke(obj, parameters);
#endregion
return Json(new { IsSuccess = true ,Result = result}, JsonRequestBehavior.AllowGet); }
catch(Exception ex)
{
return Json(new { IsSuccess =
false ,Result = ""}, JsonRequestBehavior.AllowGet);
}
    }
原文地址:https://www.cnblogs.com/LYF1997/p/10717112.html