如何获取List<T>类型对象的属性及其子元素属性名与值
未知List泛型类型时获取集合属性及元素属性值的C#实现
场景与需求
给定以下C#代码结构:
class ClassOne { public int i {get;set;} public string str {get;set;} }; class ClassTwo { public string b {get;set;} public List<ClassOne> somelist {get;set;} }; ClassOne ele = new ClassOne(); ele.i = 1; ele.str = "a"; ClassTwo two = new ClassTwo(); two.b = "b"; two.somelist = new List<ClassOne>(); two.somelist.Add(ele);
需要在未知List<T>中T具体类型的前提下,获取somelist的属性名,以及其内部元素的所有属性名与对应值,输出格式要求如下:
property: "somelist" subproperty:"i" value:1 subproperty: "str" value: "a"
实现方案
利用C#反射机制,在运行时动态获取类型与属性信息,无需提前知晓泛型参数类型。以下是具体实现代码:
核心处理方法
using System; using System.Collections; using System.Reflection; public static void PrintListPropertyDetails(object obj, string propertyName) { // 获取目标属性的元数据 PropertyInfo listProperty = obj.GetType().GetProperty(propertyName); if (listProperty == null) { Console.WriteLine($"Property {propertyName} not found."); return; } // 输出集合属性名 Console.WriteLine($"property: \"{listProperty.Name}\""); // 将属性值转为可枚举类型(兼容所有实现IEnumerable的集合) IEnumerable listValue = listProperty.GetValue(obj) as IEnumerable; if (listValue == null) { Console.WriteLine($"Property {propertyName} is not an enumerable collection."); return; } // 遍历集合内每个元素 foreach (var item in listValue) { if (item == null) continue; // 获取元素的所有公共实例属性 PropertyInfo[] itemProperties = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var prop in itemProperties) { object propValue = prop.GetValue(item); // 对字符串类型值添加引号,匹配输出格式 string valueStr = propValue is string ? $"\"{propValue}\"" : propValue?.ToString() ?? "null"; Console.WriteLine($"subproperty: \"{prop.Name}\" value: {valueStr}"); } } }
调用示例
在现有代码后添加调用语句:
PrintListPropertyDetails(two, "somelist");
输出结果
运行后将输出:
property: "somelist" subproperty:"i" value:1 subproperty: "str" value: "a"
关键逻辑说明
- 反射获取属性信息:通过
GetType().GetProperty动态获取目标集合属性的元数据,无需提前知道类型。 - 兼容集合类型:将属性值转为
IEnumerable,可处理List<T>、HashSet<T>等所有实现该接口的集合。 - 动态遍历元素属性:对集合内每个元素,再次通过反射获取其所有公共属性,输出属性名与对应值,并针对字符串类型做格式适配。
内容的提问来源于stack exchange,提问作者CBal
相关产品推荐
相关产品推荐

