scarpacci
scarpacci

Reputation: 9194

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 ");
    }
}

Upvotes: 2

Views: 7115

Answers (4)

vcsjones
vcsjones

Reputation: 141598

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.

Upvotes: 9

svick
svick

Reputation: 244757

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().

Upvotes: 4

user743382
user743382

Reputation:

In addition to the binding flags already mentioned, you appear to be trying to pass an argument to a method that doesn't take any.

Upvotes: 1

SLaks
SLaks

Reputation: 887305

You need to include BindingFlags.Instance.

Upvotes: 3

Related Questions