【问题标题】:Creating instance with parameters and involking methods from dll使用 dll 中的参数和调用方法创建实例
【发布时间】:2013-03-26 03:01:42
【问题描述】:

我正在加载一个 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. 有更好的方法吗?

【问题讨论】:

    标签: dll assembly.reflectiononly


    【解决方案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);
    

    【讨论】:

      猜你喜欢
      • 2014-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-02
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      相关资源
      最近更新 更多