2011-01-21 34 views
0

除了这样做以外,还有一种更好的方法可以确定类型是否是代表的操作之一。如何确定类型是否是Action/Func代表之一?

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

“type”这里不是一个类型对象,而是一个类型为有问题的对象的实例?这似乎是一个很容易让人误解的变量名称。 – 2011-01-21 17:07:07

+0

@Eric:你说得对,我正在尝试一些东西,通常我不会这样说。 – epitka 2011-01-21 17:09:10

回答

9

这似乎完全明了。

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的其中一个版本,您会关心什么?你将如何处理这些信息?

1
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 
} 
相关问题