How to call a method with arguments of different types using reflection in C#
I'm trying to call a function that takes two parameters (a boolean and a string) using .NET reflection in C#. However, with the following code i get an exception:
object[] paramList = new object[] { true, "Foo" };
Type wsType = typeof(MyWS);
MyWS inst = (MyWS)Activator.CreateInstance(wsType);
MethodInfo meth开发者_StackOverflow中文版od = wsType.GetMethod(function); // function = the name of the function to be called
method.Invoke(inst, paramList);
This throws an ArrayTypeMismatchException ("Attempted to access an element as a type incompatible with the array.").
It seems that paramList is causing the exception, but I have no idea why?
The function I'm trying to call would be something like:
public bool EnableSchedule(bool enable, string password)
{
...
}
It doesn't seem like there is anything wrong with what you are doing - unless the problem lies in the "MyWS". I assume the class is public. Meanwhile, try adding some binding flags to GetMethod(), like
wsType.GetMethod(function, BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance);
精彩评论