给定一个集合如何检查对象的针对一个类型列表类型?
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”关键字吗?
您应该使用的任何()而不是检查计数 –
作为一个侧面说明,我多么希望自己精神上解析像'a.IsInstanceOf(B)'为_“是B的实例? “_ - 在这种情况下当然是倒退了。 –
你确定'IsInstanceOf'是你想要的吗? 'IsAssignableFrom'听起来更像你想要的。 http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx – asawyer