【问题标题】:Loading Runtime DLL加载运行时 DLL
【发布时间】:2014-03-10 01:36:52
【问题描述】:

我正在尝试加载 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.

请帮忙。

【问题讨论】:

标签: c# dll createinstance


【解决方案1】:

似乎您正在将方法参数传递给类构造函数。

这个:

Object compObject = Activator.CreateInstance(runTimeDLLType, mthdInps); 

应该只是:

Object compObject = Activator.CreateInstance(runTimeDLLType); 

然后,你调用带有参数的方法:

string mthdResult = (string)mthdInfo.Invoke(compObject, new object[] { objs });

【讨论】:

  • 是的,我试过了......现在,我得到“参数计数不匹配”。错误。
  • @wesfaith 试试这个:(string)mthdInfo.Invoke(compObject, new object[] { objs });我已经更新了我的答案。
【解决方案2】:

Activator.CreateInstance(Type, Object[]) 的第二个参数指定构造函数的参数。您需要修改您的构造函数以采用Object[],或者仅使用TypeActivator.CreateInstance(Type) 调用它,然后在对象数组中调用您的方法。

请参阅msdn 文档。

【讨论】:

    【解决方案3】:

    试试这个:

    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 );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-24
      • 1970-01-01
      • 1970-01-01
      • 2013-03-13
      • 2011-02-27
      相关资源
      最近更新 更多