检查对象是否是一种集合,无论该集合的类型是什么?

时间:2013-09-13 20:02:34

标签: c#

我可以使用

检查单一类型
if (e.PropertyType == typeof(EntityCollection<Search_SearchCodes>))

但是我真的想避免使用EntityCollections

的所有对象
if (e.PropertyType == typeof(EntityCollection))

有办法做到这一点吗?

1 个答案:

答案 0 :(得分:8)

您可以通过确认类型是通用类型,并且其generic type definition等于EntityCollection<> open generic type来执行此操作。

var type = e.PropertyType;
var isEntityCollection = type.IsGenericType && 
    type.GetGenericTypeDefinition() == typeof(EntityCollection<>);