Type.InvokeMember执行方法时候需要按参数名对应参数值时,指定了参数名和参数值,结果传递给方法的参数值和参数名不对应,这个问题很奇怪,调用时调换了参数名和值的顺序就可以,一直不知道为什么?
调用代码:
static void Main(string[] args)
{
Comp comp = new Comp();
Dictionary<String, object> param = new Dictionary<string, object>();
param.Add(“compclass”, “compclass”);
param.Add(“compmodule”, “compmodule”);
param.Add(“compid”, “compid”);
ReflectionHelper.InvokeMethod(comp,”saveinfo”,param.Values.ToArray<Object>(),param.Keys.ToArray<String>());
Console.Read();
}
方法代码:
public ViewData SaveInfo(string compid,string compclass,string compmodule)
{
try{ //传入的compid=”compmodule” compclass=”compid” compmodule=”compclass”
return ExecuteAction(compid, “AlterInfo”);
}catch(Exception e)
{
throw e;
}
}
调换了参数顺序后,则正常运行,调换后的代码:
static void Main(string[] args)
{
Comp comp = new Comp();
Dictionary<String, object> param = new Dictionary<string, object>();
param.Add(“compclass”, “compclass”);
param.Add(“compid”, “compid”);
param.Add(“compmodule”, “compmodule”);
//param.Add(“compcontent”, “compcontent”);
ReflectionHelper.InvokeMethod(comp,”saveinfo”,param.Values.ToArray<Object>(),param.Keys.ToArray<String>());
Console.Read();
}
最终无奈了,解决办法就是,读取Method的参数数组,然后按顺序取值存入Object[]数组中,反射执行方法,代码如下:
String methodName = GetMethodName(context).ToLower();//获得方法名
MethodInfo[] methods = ReflectionHelper.GetMethods(comp);
MethodInfo method = methods.Where<MethodInfo>(m => m.Name.ToLower().Equals(methodName)).ToList<MethodInfo>()[0];
//按参数顺序取参数值
Object[] values = new Object[] { };
Array.Resize<Object>(ref values, method.GetParameters().Length);
foreach (ParameterInfo info in method.GetParameters())
{
values[info.Position]=namedParameters[info.Name];
}
ViewData viewData = method.Invoke(comp, values) as ViewData;