简体   繁体   中英

Call Non-Static method in Reflection

I can't seem to figure out how to call a Non-Static method (Instance Method) From reflection. What am I doing wrong? Really new / ignorant with reflection (If you haven't noticed):

Example:

class Program
{
    static void Main()
    {
        Type t = Type.GetType("Reflection.Order" + "1");
        var instance = Activator.CreateInstance(t);
        object[] paramsArray = new object[] { "Hello" };
        MethodInfo method = t.GetMethod("Handle", BindingFlags.InvokeMethod | BindingFlags.Public);

        method.Invoke(instance, paramsArray);

        Console.Read();
    }
}



public class Order1
{
    public void Handle()
    {
        Console.WriteLine("Order 1 ");
    }
}

You have two problems:

  1. Your BindingFlags are incorrect. It should be:

     MethodInfo method = t.GetMethod("Handle", BindingFlags.Instance | BindingFlags.Public); 

    Or you can remove the binding flags all together and use the Default Binding behavior, which will work in this case.

  2. Your Handle method as declared takes zero parameters, but you are invoking it with one parameter ( "Hello" ). Either add a string parameter to Handle:

     public void Handle(string something) { Console.WriteLine("Order 1 "); } 

    Or don't pass in any parameters.

You should use

BindingFlags.Instance | BindingFlags.Public

in your call to GetMethod() .

BindingFlags.InvokeMethod (and other invocation flags) is not used by GetMethod() . You can see what it's meant for in the documentation for Type.InvokeMember() .

您需要包含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