我正在加载一个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.有更好的方法吗?
只需要添加以下行:
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);