Ho un elenco a discesa che viene compilato esaminando i metodi di una classe e compresi quelli che corrispondono a una firma specifica. Il problema è nel prendere l'elemento selezionato dall'elenco e ottenere il delegato a chiamare quel metodo nella classe. Il primo metodo funziona, ma non riesco a capire parte del secondo.Ottenere un delegato da methodinfo
Per esempio,
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;
}
Come faccio ad avere la sezione commentata del secondo metodo di lavorare? Come faccio a trasmettere il numero MethodInfo
al delegato?
Grazie!
Modifica: Ecco la soluzione di lavoro.
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;
}
Grazie nkohari, ha funzionato esattamente come ho bisogno. –