加载运行时DLL
本文关键字:DLL 运行时 加载 | 更新日期: 2023-09-27 17:49:24
我正在尝试加载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.
请帮。
似乎您正在将方法参数传递给类构造函数。
:
Object compObject = Activator.CreateInstance(runTimeDLLType, mthdInps);
应该是:
Object compObject = Activator.CreateInstance(runTimeDLLType);
然后,你用参数调用这个方法:
string mthdResult = (string)mthdInfo.Invoke(compObject, new object[] { objs });
Activator.CreateInstance(Type, Object[])
的第二个参数指定构造函数的参数。您需要修改您的构造函数以获取Object[]
,或者仅使用Type
, Activator.CreateInstance(Type)
调用它,然后在对象数组中调用您的方法。
试试这个:
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 );