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:
Your BindingFlags are incorrect. It should be:
Or you can remove the binding flags all together and use the Default Binding behavior, which will work in this case.
Your
Handlemethod as declared takes zero parameters, but you are invoking it with one parameter ("Hello"). Either add a string parameter to Handle:Or don’t pass in any parameters.