2009-06-02 48 views
25

我有一個下拉列表,通過檢查類的方法幷包括那些匹配特定簽名來填充。問題在於從列表中選取項目並讓委託在該類中調用該方法。第一種方法有效,但我無法弄清楚第二種方法的一部分。從methodinfo獲取委託

例如,

public delegate void MyDelegate(MyState state); 

public static MyDelegate GetMyDelegateFromString(string methodName) 
{ 
    switch (methodName) 
    { 
     case "CallMethodOne": 
      return MyFunctionsClass.CallMethodOne; 
     case "CallMethodTwo": 
      return MyFunctionsClass.CallMethodTwo; 
     default: 
      return MyFunctionsClass.CallMethodOne; 
    } 
} 

public static MyDelegate GetMyDelegateFromStringReflection(string methodName) 
{ 
    MyDelegate function = MyFunctionsClass.CallMethodOne; 

    Type inf = typeof(MyFunctionsClass); 
    foreach (var method in inf.GetMethods()) 
    { 
     if (method.Name == methodName) 
     { 
      //function = method; 
      //how do I get the function to call? 
     } 
    } 

    return function; 
} 

我如何獲得第二個方法的註釋部分工作?我如何將MethodInfo投入代表?

謝謝!

編輯:這是工作解決方案。

public static MyDelegate GetMyDelegateFromStringReflection(string methodName) 
{ 
    MyDelegate function = MyFunctionsClass.CallMethodOne; 

    Type inf = typeof(MyFunctionsClass); 
    foreach (var method in inf.GetMethods()) 
    { 
     if (method.Name == methodName) 
     { 
      function = (MyDelegate)Delegate.CreateDelegate(typeof(MyDelegate), method); 
     } 
    } 

    return function; 
} 

回答

21

你需要調用Delegate.CreateDelegate()某種形式,這取決於問題的方法是靜態或實例方法。

+1

謝謝nkohari,按照我的需要制定出來。 – 2009-06-02 17:19:40

8
private static Delegate CreateDelegate(this MethodInfo methodInfo, object target) { 
    Func<Type[], Type> getType; 
    var isAction = methodInfo.ReturnType.Equals((typeof(void))); 
    var types = methodInfo.GetParameters().Select(p => p.ParameterType); 

    if (isAction) { 
     getType = Expression.GetActionType; 
    } 
    else { 
     getType = Expression.GetFuncType; 
     types = types.Concat(new[] { methodInfo.ReturnType }); 
    } 

    if (methodInfo.IsStatic) { 
     return Delegate.CreateDelegate(getType(types.ToArray()), methodInfo); 
    } 

    return Delegate.CreateDelegate(getType(types.ToArray()), target, methodInfo.Name); 
} 
+0

這應該是公認的答案:它直接解決問題 – Graviton 2017-07-15 05:04:16