0
点赞
收藏
分享

微信扫一扫

C#反射实例化类并调用带参数的方法


string method = Request["METHAD"];
string ClassNamespace = method.Substring(0, method.LastIndexOf("."));// "Bss.Web.Login";
object objType = CreateObject(Request["DLL"], ClassNamespace);
//Assembly assembly = Assembly.Load("Mobizone.BLL");
//Type type = assembly.GetType("Mobizone.BLL." + dataSource.Split('.')[0]);
//object obj = Activator.CreateInstance(type); 实例化反射类


Type ht = objType.GetType();
MethodInfo methodInfo = ht.GetMethod(method.Substring(method.LastIndexOf(".") + 1));
int length = Request.Form.AllKeys.Length;
ParameterInfo[] paramsInfo = methodInfo.GetParameters();//得到指定方法的参数列表


object[] obj = new object[length];
for (int i = 0; i < length; i++)
{
Type tType = paramsInfo[i].ParameterType;
//如果它是值类型,或者String
if (tType.Equals(typeof(string)) || (!tType.IsInterface && !tType.IsClass))
{
//改变参数类型
obj[i] = Convert.ChangeType(Request.Form[i], tType);
}
else if (tType.IsClass)//如果是类,将它的json字符串转换成对象
{
obj[i] = Newtonsoft.Json.JsonConvert.DeserializeObject(Request.Form[i], tType);
}
}
//执行方法
object returnValue = methodInfo.Invoke(objType, obj);


举报

相关推荐

0 条评论