动态调用DLL和方法与参数 [英] Dynamically calling a dll and method with arguments
问题描述
基本上我试图通过名字来称呼一个dll,实例化一个对象,然后按名称在DLL调用的方法。我发现了一个异常已被调用的目标引发异常。在Method.Invoke期间。我相当肯定我的问题是有方法的参数类型转换。我想知道是否有人对这个例外的任何输入。此外,在如何修改我的做法有任何建议都欢迎。
公共无效calldll(字符串DLLNAME,字符串的typeName,字符串methodName中,字符串参数){
的String [] = argumentArray arguments.Split(新的char [] {'|'},StringSplitOptions.None);
装配装配= Assembly.LoadFrom(DLLNAME);
类型的System.Type = assembly.GetType(typeName的);
对象o = Activator.CreateInstance(类型);
MethodInfo的方法= type.GetMethod(方法名);
的ParameterInfo [] =参数method.GetParameters();
对象[] = methodParameters新的对象[parameters.GetLength(0)];
的for(int i = 0; I< parameters.Length - 1;我++)
{
VAR器= TypeDescriptor.GetConverter(参数[I] .GetType() );
methodParameters [I] = converter.ConvertFrom(argumentArray [I]);
}
method.Invoke(邻,methodParameters); }
我发现你的代码的两个问题:
- 您不是遍历所有的
参数
。您应该删除1
从为
循环。 - 当你创建转换器,可以调用
的GetType()
方法。这将返回键入
的的ParameterInfo
的对象,而不是键入
参数。使用属性参数类型
代替。
所有的一切,改变第一线在为
循环,这样的:
的for(int i = 0 ; I< parameters.Length;我++)
{
VAR器= TypeDescriptor.GetConverter(参数[I] .ParameterType);
一旦你完成了这些修正,我相信你的代码应该运行按预期。至少它为我做的,当我测试了一个简单的无效你好(INT X,y字符串)
方法。
Basically I'm trying to call a dll by name, instantiate an object, then call a method by name in that dll. I'm getting an "Exception has been thrown by the target of an invocation." during the Method.Invoke. I'm fairly sure my problem is with the typecasting of the arguments of the method. I was wondering if anyone had any input on this exception. Additionally, any suggestions on how to revise my approach are welcome.
public void calldll(string dllName, string typeName, string methodName, string arguments) {
string[] argumentArray = arguments.Split(new char[] { '|' }, StringSplitOptions.None);
Assembly assembly = Assembly.LoadFrom(dllName);
System.Type type = assembly.GetType(typeName);
Object o = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod(methodName);
ParameterInfo[] parameters = method.GetParameters();
object[] methodParameters = new object[parameters.GetLength(0)];
for (int i = 0; i < parameters.Length - 1; i++)
{
var converter = TypeDescriptor.GetConverter(parameters[i].GetType());
methodParameters[i] = converter.ConvertFrom(argumentArray[i]);
}
method.Invoke(o, methodParameters); }
I found two issues with your code:
- You are not looping over all
parameters
. You should remove-1
from thefor
loop. - When you are creating your converter, you call the
GetType()
method. This returns theType
of theParameterInfo
object, not theType
of the parameter. Use the propertyParameterType
instead.
All in all, change the first lines in the for
loop to this:
for (int i = 0; i < parameters.Length; i++)
{
var converter = TypeDescriptor.GetConverter(parameters[i].ParameterType);
Once you have done these corrections, I believe your code should run as intended. At least it did for me when I tested a simple void Hello(int x, string y)
method.
这篇关于动态调用DLL和方法与参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!