我正在尝试加载DLL运行时并在DLL中存在的一个类中调用方法。
这是我加载DLL和调用方法的地方,
Object[] mthdInps = new Object[2];
mthdInps[0] = mScope;
string paramSrvrName = srvrName;
mthdInps[1] = paramSrvrName;
Assembly runTimeDLL = Assembly.LoadFrom("ClassLibrary.dll");
Type runTimeDLLType = runTimeDLL.GetType("ClassLibrary.Class1");
Object compObject = Activator.CreateInstance(runTimeDLLType, mthdInps);
Type compClass = compObject.GetType();
MethodInfo mthdInfo = compClass.GetMethod("Method1");
string mthdResult = (string)mthdInfo.Invoke(compObject, null);
这是我试图调用的类(存在于DLL中)及其方法,
namespace ClassLibrary
{
public class Class1
{
public Class1() {}
public String Method1(Object[] inpObjs)
{
}
}
}
我得到的错误就是这个,
的 Constructor on type 'ClassLibrary.Class1' not found.
请帮忙。
答案 0 :(得分:3)
似乎您正在将方法参数传递给类构造函数。
此:
Object compObject = Activator.CreateInstance(runTimeDLLType, mthdInps);
应该只是:
Object compObject = Activator.CreateInstance(runTimeDLLType);
然后,使用参数调用方法:
string mthdResult = (string)mthdInfo.Invoke(compObject, new object[] { objs });
答案 1 :(得分:1)
Activator.CreateInstance(Type, Object[])
的第二个参数指定构造函数的参数。您需要修改构造函数以获取Object[]
,或仅使用Type
,Activator.CreateInstance(Type)
调用它,然后调用传入对象数组的方法。
请参阅msdn文档。
答案 2 :(得分:0)
试试这个:
Object[] mthdInps = new Object[2];
mthdInps[0] = mScope;
string paramSrvrName = srvrName;
mthdInps[1] = paramSrvrName;
Assembly runTimeDLL = Assembly.LoadFrom("ClassLibrary.dll");
Type runTimeDLLType = runTimeDLL.GetType("ClassLibrary.Class1");
//do not pass parameters if the constructor doesn't have
Object compObject = Activator.CreateInstance(runTimeDLLType);
Type compClass = compObject.GetType();
MethodInfo mthdInfo = compClass.GetMethod("Method1");
// one parameter of type object array
object[] parameters = new object[] { mthdInps };
string mthdResult = (string)mthdInfo.Invoke(compObject, parameters );