Reputation: 9194
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
Reputation: 141598
You have two problems:
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.
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
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
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