Reputation: 21366
How can we exacute a method and get the return value from Reflection.
Type serviceType = Type.GetType("class", true);
var service = Activator.CreateInstance(serviceType);
serviceType.InvokeMember("GetAll", BindingFlags.InvokeMethod, Type.DefaultBinder, service, null);
Upvotes: 2
Views: 8387
Reputation: 1705
I am not sure whether you are interested on the return value or the return Type. Well both are answered by the code below, where I try to execute the sum method and get the value as well as the Type of the return value:
class Program
{
static void Main(string[] args)
{
var svc = Activator.CreateInstance(typeof(Util));
Object ret = typeof(Util).InvokeMember("sum", BindingFlags.InvokeMethod, Type.DefaultBinder, svc, new Object[] { 1, 2 });
Type t = ret.GetType();
Console.WriteLine("Return Value: " + ret);
Console.WriteLine("Return Type: " + t);
}
}
class Util
{
public int sum(int a, int b)
{
return a + b;
}
}
Upvotes: 4
Reputation: 12552
You can try something like this:
ConstructorInfo constructor = Type.GetType("class", true).GetConstructor(Type.EmptyTypes);
object classObject = constructor.Invoke(new object[]{});
MethodInfo methodInfo = Type.GetType("class", true).GetMethod("GetAll");
object returnValue = methodInfo.Invoke(classObject , new object[] { });
I haven't compiled it, but it should work.
Upvotes: 0
Reputation: 33252
cast the InvokeMember result to the type actually returned by the method call.
Upvotes: 1
Reputation: 560
http://msdn.microsoft.com/en-us/library/de3dhzwy.aspx
"Return Value
Type: System.Object
An object representing the return value of the invoked member."
Upvotes: 1