2
問題:如何檢查T
類型,其中T
或者是Action
或Func
的MethodInfo
比賽Delegate
?如何檢查MethodInfo是否匹配泛型類型T的委託,其中T是Action還是Func?
Assembly
的用例
代碼示例,其應匹配T
類型的Delegate
:
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);
}
}
}
功能調用示例:
var functions = new Dictionary<string, Func<int, int>>();
AddScriptFunctions(Assembly.GetExecutingAssembly(), functions);
var functions2 = new Dictionary<string, Action>();
AddScriptFunctions(Assembly.GetExecutingAssembly(), functions2);
注:沒有將Delegate.CreateDelegate
放入try/catch塊。