我有一個下拉列表,通過檢查類的方法幷包括那些匹配特定簽名來填充。問題在於從列表中選取項目並讓委託在該類中調用該方法。第一種方法有效,但我無法弄清楚第二種方法的一部分。從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;
}
謝謝nkohari,按照我的需要制定出來。 – 2009-06-02 17:19:40