Reflection, Get return value from a method

和自甴很熟 提交于 2021-01-28 19:38:44

问题


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

回答1:


cast the InvokeMember result to the type actually returned by the method call.




回答2:


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



回答3:


http://msdn.microsoft.com/en-us/library/de3dhzwy.aspx

"Return Value

Type: System.Object

An object representing the return value of the invoked member."




回答4:


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.



来源:https://stackoverflow.com/questions/5405568/reflection-get-return-value-from-a-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!