Dynamic call of dll and method with arguments

I basically try to call the dll by name, instantiate the object, and then call the method by name in this DLL. I get "The exception was selected as the target of the call." during the method. I am sure my problem is with typing method arguments. I was wondering if there is anyone in this exception. In addition, any suggestions on how to reconsider 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); } 
+6
source share
1 answer

I found two problems with your code:

  • You do not iterate over all parameters . You must remove -1 from the for loop.
  • When you create the converter, you call the GetType() method. This returns the Type of the ParameterInfo object, not the Type parameter. Use the ParameterType property instead.

In general, change the first lines of the for loop to this:

 for (int i = 0; i < parameters.Length; i++) { var converter = TypeDescriptor.GetConverter(parameters[i].ParameterType); 

Once you make these corrections, I believe that your code should work as intended. At least that was for me when I tested the simple void Hello(int x, string y) method void Hello(int x, string y) .

+4
source

Source: https://habr.com/ru/post/922475/


All Articles