使用dll中的参数和aggking方法创建实例

时间:2013-03-26 03:01:42

标签: dll assembly.reflectiononly

我正在加载一个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 个答案:

答案 0 :(得分: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);