问题: 如何检查MethodInfo
是否与类型为T
的Delegate
相匹配,其中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块中时。
: Delegate
约束来降低未接收到委托类型的可能性。 - nalka