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

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

if(obj is MulticastDelegate && obj.GetType().FullName.StartsWith("System.Action")) { ... } 

这看起来非常简单。

 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; } 

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

  private static readonly HashSet _set = new HashSet { typeof(Action), typeof(Action<>), typeof(Action<,>), // etc typeof(Func<>), typeof(Func<,>), typeof(Func<,,>), // etc }; // ... Type t = type.GetType(); if (_set.Contains(t) || (t.IsGenericType && _set.Contains(t.GetGenericTypeDefinition()))) { // yep, it's one of the action or func delegates }