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

如何获取C#类实例中嵌套类属性的名称与对应值?

嵌套类属性自动遍历与输出实现

需求:自动遍历嵌套类实例的所有属性,生成带层级的属性名(如dutTestData.gpioData.pin_mosi_toGnd)和对应值,输出到文本文件,无需手动编写每个变量的字符串。

实现代码

工具类:属性遍历与文件写入

using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;

public static class ObjectPropertyPrinter
{
    // 递归收集所有嵌套属性的路径与值
    public static List<string> GetNestedProperties(object obj, string parentPath = "")
    {
        var result = new List<string>();
        if (obj == null) return result;

        Type type = obj.GetType();
        // 获取对象的所有公共实例属性
        PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (PropertyInfo prop in properties)
        {
            // 跳过不需要的属性(比如BitsAll,可根据需求调整)
            if (prop.Name == "BitsAll") continue;

            // 拼接当前属性的完整路径
            string currentPath = string.IsNullOrEmpty(parentPath) ? prop.Name : $"{parentPath}.{prop.Name}";
            object value = prop.GetValue(obj);

            // 值类型/字符串直接输出,引用类型递归遍历
            if (prop.PropertyType.IsValueType || prop.PropertyType == typeof(string))
            {
                result.Add($"{currentPath} = {value}");
            }
            else
            {
                result.AddRange(GetNestedProperties(value, currentPath));
            }
        }

        return result;
    }

    // 将属性列表写入指定文本文件
    public static void WritePropertiesToFile(List<string> properties, string filePath)
    {
        File.WriteAllLines(filePath, properties);
    }
}

调用示例

// 创建实例并赋值
DutTestdata dutTestData = new DutTestdata();
dutTestData.gpioData.pin_mosi_toGnd = false;
dutTestData.gpioData.pin_mosi_toVdd = true;

// 或者通过Testdata方法赋值
// byte[] testData = ...; // 传入实际数据
// dutTestData.Testdata(testData, TestData.GPIO_BITS);

// 获取所有嵌套属性
var propertyLines = ObjectPropertyPrinter.GetNestedProperties(dutTestData, "dutTestData");

// 控制台预览输出
foreach (var line in propertyLines)
{
    Console.WriteLine(line);
}

// 写入文本文件
ObjectPropertyPrinter.WritePropertiesToFile(propertyLines, "DutTestData_Output.txt");

输出结果

运行后,DutTestData_Output.txt的内容如下:

dutTestData.gpioData.pin_mosi_toGnd = False
dutTestData.gpioData.pin_mosi_toVdd = True

如果需要调整输出格式(比如去掉实例名dutTestData,只保留gpioData.pin_mosi_toGnd),只需修改调用时的parentPath参数:

var propertyLines = ObjectPropertyPrinter.GetNestedProperties(dutTestData.gpioData, "gpioData");

输出会变成:

gpioData.pin_mosi_toGnd = False
gpioData.pin_mosi_toVdd = True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 13:54:55