0

我正在加载一个 dll,创建一个实例并想要调用方法并检查返回值。创建实例时出现异常 {"Parameter count mismatch."}:

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

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

4

1 回答 1

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);
于 2013-03-26T22:36:45.857 回答