反射方法调用时的一个错误:参数计数不匹配( parameter count mismatch )

大致情况是这样,我在一个DLL定义了一个方法A,A的参数为一个参数数组;

然后使用反射调用其中的方法A,并且传递一个object数组到方法A

大致代码如下:

 

代码
//获取程序集
currentAssembly = Assembly.LoadFrom(System.AppDomain.CurrentDomain.BaseDirectory + "\\" + System.Configuration.ConfigurationManager.AppSettings["PluginCatalog"+ "\\" + requestedNameSpace + "\\" + requestedNameSpace + ".dll");

//获取命名空间和类名
currentType = currentAssembly.GetType(requestedNameSpace + "." + requestedClassName);

//获取方法的名称
currentMethod = currentType.GetMethod(requestedMethodName);

//创建实例对象
currentInstance = currentAssembly.CreateInstance(requestedNameSpace + "." + requestedClassName);

//具体方法的调用并传入方法数组
 StrinForBack = (string)currentMethod.Invoke(currentInstance, postedParams);

 

 

这样如果你直接把接收到的参数数组postedParams直接传递给invoke方法的话,就会产生标题所述的错误;

后来查阅MSDN,这个帖子让我茅塞顿开

Parameter count mismatch

应该这样理解:Invoke方法的参数当中有一个自己的object[],正好你传递的参数也是object[],这样的话invoke就会把你参数数组里面的第一个参数作为参数传递给你要调用的方法,于是就报错了。

解决问题的如下:

postedParams = new object[] { postedParams };

StrinForBack = (string)currentMethod.Invoke(currentInstance, postedParams);

╮(╯_╰)╭

posted @ 2010-04-21 18:47  二叉树  阅读(15415)  评论(1编辑  收藏  举报