Ian Boyd
Ian Boyd

Reputation: 256581

How to call a MethodInfo?

i have a MethodInfo object, that defines a method i want to call.

Except i need the object that MethodInfo came from.

pseudo-code:

void CallMethod(MethodInfo m)
{
    Object o = Activator.CreateInstance(m.ClassType);
    o.GetType().InvokeMember(m.Name, BindingFlags.InvokeMethod, null, o, null);
}

Except i don't know how to get the type of the class that MethodInfo belongs to.

How can i call a MethodInfo?

Upvotes: 0

Views: 1321

Answers (4)

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68667

This will create an object from the type that your MethodInfo is, and will invoke it for you on that new object.

void CallMethod(MethodInfo m)
{
    Object o = Activator.CreateInstance(m.ReflectedType);
    m.Invoke(o, null);
}

Upvotes: 2

Hand-E-Food
Hand-E-Food

Reputation: 12794

I may be misunderstanding the question, but it sounds like you're after a delegate rather than a MethodInfo.

void Main()
{
    Object myObject = new ArrayList();
    MethodInfo methodInfo = myObject.GetType().GetMethod("Clear");
    Delegate method = Delegate.CreateDelegate(typeof(Action), myObject, methodInfo, true);
    CallMethod(method);
}

void CallMethod(Delegate method)
{
    method.DynamicInvoke();
}

There's clearly an easier way to acquire the delegate in this circumstance (method = new Action(myObject.Clear)), but I'm going on your question of needing to use a MethodInfo object.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499770

The MethodInfo doesn't know the target of the method call - the MethodInfo effectively belongs to the type, not one specific object.

You need to have an instance of the target type on which to call the method. You can find the type easily enough using MethodInfo.DeclaringType (inherited from MemberInfo.DeclaringType), but you may not have an instance at that point...

As noted by Reed, MemberInfo.ReflectedType may be more appropriate than DeclaringType, depending on how you were planning to use it.

You haven't explained anything about what you're doing, but it may be more appropriate to take an Action delegate instead of a MethodInfo, if the rest of your design could be changed appropriately.

Upvotes: 5

M.Babcock
M.Babcock

Reputation: 18965

You can determine the type which defines the method by accessing the DeclaringType property of the MethodInfo object.

Upvotes: 0

Related Questions