简体   繁体   中英

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 method = 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM