2011-03-23 121 views
1

我們如何可以取得一個方法並從Reflection獲取返回值。反射,從方法獲取返回值

Type serviceType = Type.GetType("class", true); 
var service = Activator.CreateInstance(serviceType); 
serviceType.InvokeMember("GetAll", BindingFlags.InvokeMethod, Type.DefaultBinder, service, null); 

回答

1

將InvokeMember結果轉換爲方法調用實際返回的類型。

0

你可以嘗試這樣的事情:

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[] { }); 

我沒有編譯它,但它應該工作。

4

我不確定您對返回值還是返回類型感興趣。 這兩個都是由下面的代碼回答,我嘗試執行求和方法並獲得值以及返回值的類型:

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