C#如何获取返回值为指定基类或其派生类IEnumerable类型的类属性
C# 实现获取指定类中符合条件的IEnumerable属性方案
核心逻辑
- 反射读取目标类的所有公共属性,可通过调整
BindingFlags参数适配静态/非公开属性的查询需求 - 过滤出返回值为泛型类型,且泛型类型定义为
IEnumerable<>的属性 - 取出
IEnumerable<T>的泛型参数T,判断T是否可赋值给指定的基类类型,满足条件则返回对应的PropertyInfo
完整实现代码
using System.Reflection; using System.Collections.Generic; using System.Linq; public static IEnumerable<PropertyInfo> GetIEnumerablePropertiesOfType(Type targetClassType, Type elementBaseType) { return targetClassType.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(prop => { // 过滤非泛型返回值的属性 if (!prop.PropertyType.IsGenericType) return false; // 过滤泛型定义不是IEnumerable<>的属性 var genericTypeDefinition = prop.PropertyType.GetGenericTypeDefinition(); if (genericTypeDefinition != typeof(IEnumerable<>)) return false; // 获取IEnumerable的元素类型 var elementType = prop.PropertyType.GetGenericArguments()[0]; // 判断元素类型是否属于指定基类的继承链 return elementBaseType.IsAssignableFrom(elementType); }); }
调用示例
// 示例调用,返回Prop1、Prop2对应的PropertyInfo列表 var properties = GetIEnumerablePropertiesOfType(typeof(MyClass), typeof(MyPropBaseClass));
扩展说明
如果需要匹配返回值为List<T>、ICollection<T>等所有实现了IEnumerable<T>接口的属性,可将泛型类型判断逻辑替换为遍历属性返回类型实现的所有泛型接口,查找是否存在IEnumerable<>的构造类型,再取对应泛型参数判断即可。
内容的提问来源于stack exchange,提问作者Jonny
相关产品推荐
相关产品推荐

