我在想你可能想检查属性实现的类型的接口。(删除了冗余接口,因为 IList 继承 ICollection 而 ICollection 继承 IEnumerable。)
static void DoSomething<T>()
{
List<Type> collections = new List<Type>() { typeof(IEnumerable<>), typeof(IEnumerable) };
foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
{
if (propertyInfo.PropertyType != typeof(string) && propertyInfo.PropertyType.GetInterfaces().Any(i => collections.Any(c => i == c)))
{
continue;
}
Console.WriteLine(propertyInfo.Name);
}
}
我添加了不拒绝字符串的代码,因为它也实现了 IEnumerable,我想您可能希望保留这些代码。
鉴于之前的集合接口列表的冗余,像这样编写代码可能更简单
static void DoSomething<T>()
{
foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
{
if (propertyInfo.PropertyType != typeof(string)
&& propertyInfo.PropertyType.GetInterface(typeof(IEnumerable).Name) != null
&& propertyInfo.PropertyType.GetInterface(typeof(IEnumerable<>).Name) != null)
{
continue;
}
Console.WriteLine(propertyInfo.Name);
}
}