如何确定类型是否是Action/Func委托之一?

epi*_*tka 3 c# types

除此之外还有一种更好的方法来确定type是否是Action <>委托之一.

if(obj is MulticastDelegate && obj.GetType().FullName.StartsWith("System.Action"))
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

Eri*_*ert 13

这看起来非常简单.

static bool IsAction(Type type)
{
    if (type == typeof(System.Action)) return true;
    Type generic = null;
    if (type.IsGenericTypeDefinition) generic = type;
    else if (type.IsGenericType) generic = type.GetGenericTypeDefinition();
    if (generic == null) return false;
    if (generic == typeof(System.Action<>)) return true;
    if (generic == typeof(System.Action<,>)) return true;
    ... and so on ...
    return false;
}
Run Code Online (Sandbox Code Playgroud)

我很好奇为什么你想知道这个.如果特定类型恰好是Action的某个版本,您关心什么?你打算怎么处理这些信息?