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

3

除了这种方法,是否有更好的方法来确定类型是否是Action<>委托之一。

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

4
这里的"type"不是类型对象,而是指其类型存在疑问的对象的实例?这个变量名起得非常具有误导性。 - Eric Lippert
@Eric:你说得对,我在尝试一些东西,通常我不会这样命名。 - epitka
2个回答

14

这看起来非常简单。

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的版本之一,你为什么在意呢?你打算用这些信息做什么?


我正在使用一个名为“Clay”的库进行编程实验,我想将Action/Func类型的属性附加到动态的Clay对象上。长话短说... - epitka
1
仅检查 type.BaseType == typeof(MulticastDelegate) 是否足够? - AshleyF
@AshleyF:我不太明白你的思路。这个问题是关于识别动作和函数委托,而不是识别任何委托。你能澄清一下这个问题吗? - Eric Lippert

3
 private static readonly HashSet<Type> _set = new HashSet<Type>
     {
         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
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接