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

如何在C#中获取类的嵌套属性并生成层级字符串列表?

问题:获取实体类的嵌套属性路径字符串列表

实体类定义

(注:修正了原代码中缺少属性类型的笔误,确保可编译)

public class Country
{
    public int Id;
    public string name;
    public string code;
}
public class City
{
    public int Id;
    public string name;
    public Country country { get; set; }
}
public class Person
{
    public int Id;
    public string name;
    public DateTime dob;
    public string gender;
    public City city { get; set; }
}

期望输出

需要生成包含所有嵌套属性的完整路径字符串列表:

"Id"
"name"
"dob"
"gender"
"city.Id"
"city.name"
"city.country.Id"
"city.country.name"
"city.country.code"

当前实现及问题

现有方法仅能获取一级属性,无法遍历嵌套的引用类型属性:

private List<string> GetProps(Type type)
{
    var result=new List<string>();
    var properties = type.GetProperties().ToDictionary(x => x, x => x.GetType().GetProperties());
    foreach (var item in properties)
    {
        result.Add(item.Key.ToString());
    }
    return result;
}

GetProps(typeof(Person)); // 调用方法

返回结果仅包含一级属性:

"Id"
"name"
"dob"
"gender"
"city"

解决方案

通过递归遍历实现嵌套属性路径的获取,同时处理字段和属性(适配用户实体类的混合定义),代码如下:

private List<string> GetNestedProperties(Type type, string parentPath = "")
{
    var result = new List<string>();
    // 获取所有公共实例成员:包含字段和属性
    var members = type.GetMembers(BindingFlags.Public | BindingFlags.Instance)
                     .Where(m => m.MemberType is MemberTypes.Property or MemberTypes.Field);

    foreach (var member in members)
    {
        Type memberType = member switch
        {
            PropertyInfo prop => prop.PropertyType,
            FieldInfo field => field.FieldType,
            _ => null
        };

        if (memberType == null) continue;

        // 拼接当前成员的完整路径
        string currentPath = string.IsNullOrEmpty(parentPath) 
            ? member.Name 
            : $"{parentPath}.{member.Name}";

        // 判断是否需要递归:排除值类型、字符串、DateTime等无需拆解的类型
        bool shouldRecurse = memberType.IsClass 
            && memberType != typeof(string) 
            && memberType != typeof(DateTime);

        if (shouldRecurse)
        {
            // 递归获取嵌套成员的路径
            result.AddRange(GetNestedProperties(memberType, currentPath));
        }
        else
        {
            // 直接添加当前路径(带引号)
            result.Add($"\"{currentPath}\"");
        }
    }

    return result;
}

调用示例

var nestedProps = GetNestedProperties(typeof(Person));
foreach (var prop in nestedProps)
{
    Console.WriteLine(prop);
}

关键说明

  1. 兼容字段与属性:用户实体类混合使用了字段(如Country.Id)和属性(如City.country),代码通过GetMembers同时处理两者。
  2. 递归终止逻辑:当成员类型为值类型、string或DateTime时,直接生成路径;仅对自定义引用类型进行递归遍历。
  3. 路径拼接:通过parentPath参数传递父级路径,自动生成xxx.yyy.zzz格式的嵌套路径。

输出结果

运行后将生成完全符合期望的字符串列表。


内容的提问来源于stack exchange,提问作者Prasanna Kumar J

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:15:31