jeudi 5 février 2015

How to check that MethodInfo matches Delegate of generic type T, where T is either Action or Func?

Question: How to check that MethodInfo matches Delegate of type T, where T is either Action or Func?


Code sample with the use case of getting all static functions out of an Assembly which should match the Delegate of type T:



void AddScriptFunctions<T>(Assembly assembly, Dictionary<string, T> funMap) where T: class
{
foreach(Type type in assembly.GetTypes())
{
var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Static);
foreach(MethodInfo method in methods)
{
// How to check that MethodInfo can be converted into delegate of type T
// where T is Func<...> or Action<...>
if( ........ )
{
var function = (T)(object)Delegate.CreateDelegate(typeof(T), method);
funMap.Add(method.Name.ToLower(), function);
}
}

}


Function invocation examples:



var functions = new Dictionary<string, Func<int, int>>();
AddScriptFunctions(Assembly.GetExecutingAssembly(), functions);

var functions2 = new Dictionary<string, Action>();
AddScriptFunctions(Assembly.GetExecutingAssembly(), functions2);


Note: without enclosing Delegate.CreateDelegate into an try/catch block.






Aucun commentaire:

Enregistrer un commentaire