Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Non-Static method in Reflection

Tags:

c#

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 ");
    }
}
like image 849
scarpacci Avatar asked Sep 22 '26 04:09

scarpacci


1 Answers

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.

like image 102
vcsjones Avatar answered Sep 24 '26 20:09

vcsjones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!