You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已掌握Reflection获取类属性名值,属性为其他类数组时如何处理?

解决反射获取嵌套数组类属性的问题

没问题,我来帮你搞定这个嵌套数组的反射取值需求!你已经掌握了基础的反射获取属性方法,只需要给逻辑加个**递归处理嵌套类型(包括数组)**的分支就行。

完整解决方案代码

首先补全你代码里用到的Characteristic类,然后写一个通用的反射遍历方法:

using System;
using System.Collections;
using System.Reflection;

// 定义你的Characteristic类
public class Characteristic
{
    public string Name { get; set; }
    public string Value { get; set; }
}

class Program
{
    static void Main()
    {
        var person = new 
        { 
            Name = "John", 
            Characteristic = new[] 
            { 
                new Characteristic {Name = "Age", Value = "31"}, 
                new Characteristic {Name = "Height", Value = "6'1""} 
            } 
        };

        // 调用递归方法遍历所有属性
        TraverseProperties(person);
    }

    static void TraverseProperties(object obj, string indent = "")
    {
        if (obj == null) return;

        Type type = obj.GetType();
        PropertyInfo[] properties = type.GetProperties();

        foreach (var property in properties)
        {
            object value = property.GetValue(obj);

            // 处理数组/可枚举类型(排除string,因为string本身也是IEnumerable但不需要拆分)
            if (value != null && value is IEnumerable enumerable && !(value is string))
            {
                Console.WriteLine($"{indent}{property.Name}:");
                int index = 0;
                foreach (var item in enumerable)
                {
                    Console.WriteLine($"{indent}  元素[{index}]:");
                    // 递归遍历数组元素的属性
                    TraverseProperties(item, indent + "    ");
                    index++;
                }
            }
            else
            {
                // 普通属性直接输出名称和值
                Console.WriteLine($"{indent}{property.Name}: {value ?? "null"}");
            }
        }
    }
}

代码说明

  1. 递归核心方法TraverseProperties:

    • 先判断传入对象是否为空,为空直接返回
    • 获取对象的所有属性并逐个遍历
    • 对属性值做判断:如果是可枚举类型且不是字符串,就遍历数组/集合里的每个元素,递归调用自身处理元素的内部属性
    • 普通属性直接输出名称和对应的值
  2. 运行输出示例:

Name: John
Characteristic:
  元素[0]:
    Name: Age
    Value: 31
  元素[1]:
    Name: Height
    Value: 6'1"

这个逻辑不仅能处理数组,就算后续遇到多层嵌套的类实例,也能一层层把属性名称和值都取出来!

内容的提问来源于stack exchange,提问作者kroe761

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:00:55