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

cos*_*ost 2 c#

我可以通过使用检查单一类型

if (e.PropertyType == typeof(EntityCollection<Search_SearchCodes>))
Run Code Online (Sandbox Code Playgroud)

但我真的想避免所有的对象 EntityCollections

if (e.PropertyType == typeof(EntityCollection))
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

Jon*_*Jon 8

您可以通过确认类型是泛型类型,并且其泛型类型定义等于EntityCollection<> 开放泛型类型来执行此操作.

var type = e.PropertyType;
var isEntityCollection = type.IsGenericType && 
    type.GetGenericTypeDefinition() == typeof(EntityCollection<>);
Run Code Online (Sandbox Code Playgroud)