2

给定一个集合

IEnumerable<Type> supportedTypes

检查给定对象是否是这些类型之一(或派生类型)的最佳方法是什么?

我的第一个直觉是做类似的事情:

// object target is a parameter passed to the method in which I'm doing this.
if (supportedTypes.Count( supportedType => target is supportedType ) > 0)
{
    // Yay my object is of a supported type!!!
}

..但这似乎不起作用。我不能在这样的 lambda 表达式中使用“is”关键字吗?

4

2 回答 2

2

好的,所以在输入问题并进行更多实验以确保我没有问一些非常愚蠢的问题的过程中,我意识到了一个简单的解决方案。在这里发帖以防其他人做过同样愚蠢的事情。;-)

您不能在 lambda 表达式中使用“is”关键字,但可以使用:

supportedType => supportedType.IsInstanceOfType(target)

产生:

if (supportedTypes.Count( supportedType => 
supportedType.IsInstanceOfType(target)) > 0)

if (supportedTypes.Any( supportedType => 
                              supportedType.IsInstanceOfType(target)))
// object target is a parameter passed to the method in which I'm doing this.
{
    // Yay my object is of a supported type!!!
}

向 Bob Vale 致敬,因为他在下面的评论中指出我应该使用 .Any(...) 而不是 .Count(...) > 0

于 2012-10-26T22:29:25.963 回答
2

Why don't you use Contains and target.GetType?

bool ar isSupported = supportedTypes.Contains(target.GetType());

or Any

bool isSupported = supportedTypes.Any(t => t == target.GetType());

(don't use Enumerable.Count if you just want to know if a sequence contains a matching element, that is rather inefficient if the sequnce is large or the predicate is expensive)

Edit: If you want to take inheritance into account you can use Type.IsAssignableFrom:

var isSupported = supportedTypes.Any(t => target.GetType().IsAssignableFrom(t));
  • The is operator is used to check whether an instance is compatible to a given type.
  • The IsAssignableFrom method is used to check whether a Type is compatible with a given type.

Determines whether an instance of the current Type can be assigned from an instance of the specified Type.

于 2012-10-26T22:38:39.757 回答