2013-03-26 68 views
0

我正在加载一个dll,创建一个实例并希望调用方法并检查返回值。我得到一个异常{“参数计数不匹配。”}创建实例时:使用dll的参数和启发参数方法创建实例

static void Main(string[] args) 
    { 

      ModuleConfiguration moduleConfiguration = new ModuleConfiguration(); 

      // get the module information 
      if (!moduleConfiguration.getModuleInfo()) 
       throw new Exception("Error: Module information cannot be retrieved"); 


      // Load the dll 
      string moduledll = Directory.GetCurrentDirectory() + "\\" + 
                 moduleConfiguration.moduleDLL; 
      testDLL = Assembly.LoadFile(moduledll); 

      // create the object 
      string fullTypeName = "MyNameSpace."+ moduleConfiguration.moduleClassName; 
      Type moduleType = testDLL.GetType(fullTypeName); 

      Type[] types = new Type[1]; 
      types[0] = typeof(string[]); 

      ConstructorInfo constructorInfoObj = moduleType.GetConstructor(
         BindingFlags.Instance | BindingFlags.Public, null, 
         CallingConventions.HasThis, types, null); 

      if (constructorInfoObj != null) 
      { 
       Console.WriteLine(constructorInfoObj.ToString()); 
       constructorInfoObj.Invoke(args); 
      } 

The constructor for the class in dll is: 
public class SampleModule:ModuleBase 
{ 
    /// <summary> 
    /// Initializes a new instance of the <see cref="SampleModule" /> class. 
    /// </summary> 
    public SampleModule(string[] args) 
     : base(args) 
    { 
     Console.WriteLine("Creating SampleModule"); 
    } 

Qs的: 1.我在做什么错? 2.如何获取方法,调用它并获取返回值? 3.有没有更好的方法来做到这一点?

回答

1

只是需要添加下列行:

Object[] param = new Object[1] { args }; 

之前:

constructorInfoObj.Invoke(args); 

替代(短)溶液在不使用ConstructorInfo:

 : 

     // create the object 
     string fullTypeName = "MyNameSpace."+ moduleConfiguration.moduleClassName; 
     Type moduleType = testDLL.GetType(fullTypeName); 

     Object[] param = new Object[1] { args }; 
     Activator.CreateInstance(runnerType, param); 
相关问题