首页 > 解决方案 > 如何递归地和反射地获取所有可能的字段名称路径的列表?

问题描述

我正在尝试获取一个字符串集合,该集合为我提供了所有班级成员的字段名称,以.s 分隔。例如:

public class Apple
{
    public Banana MyBanana = new Banana();
    public Cranberry MyCranberry = new Cranberry();
}

public class Banana
{
    public int MyNumber = 5;
    public Cranberry MyCranberry = new Cranberry();
}

public class Cranberry
{
    public string MyString = "Hello!";
    public int MyOtherNumber = 10;
}

public class Demo
{
    public List<string> GetFields(Type Apple)
    {
        //I can't figure this out
        //But it should return a list with these elements:
        var result = new List<string>
        {
            "MyBanana.MyNumber",
            "MyBanana.MyCranberry.MyString",
            "MyBanana.MyCranberry.MyOtherNumber",
            "MyCranberry.MyString",
            "MyCranberry.MyOtherNumber"
        };
        return result;
    }
}

我相信需要某种递归和反射,但是在编写了几个小时功能失调的代码之后,我需要一些帮助。

我需要这个的原因是因为我正在访问使用这些文件路径作为它们各自值的键的第三方代码。

一次失败尝试的示例:

    private List<string> GetFields(Type type)
    {
        var results = new List<string>();
        var fields = type.GetFields();
        foreach (var field in fields)
        {
            string fieldName = field.Name;
            if (field.ReflectedType.IsValueType)
            {
                results.Add(fieldName);
            }
            else
            {
                results.Add(field.Name + GetFields(field.FieldType));
            }
        }
        return results;
    }

我发现了几个相关的问题,但没有一个完全符合我的问题,而且我自己也无法跳出: Recursively Get Properties & Child Properties Of A Classhttps://stackoverflow.c “om/questions/6196413/ how-to-recursively-print-the-values-of-an-objects-properties-using-reflection, Recursively Get Properties & Child Properties Of An Object , .NET, C#, Reflection: 列出一个字段的字段,它本身, 有字段

标签: c#recursionreflectionkey-value

解决方案


您需要一个递归实现:

HashSet<Type> nonRecursiveTypes = new HashSet<Type> { typeof(System.Int32), typeof(System.String) }; // add other simple types here
IEnumerable<string> GetFields(object obj)
{
    foreach (var field in obj.GetType().GetFields())
    {
        if (nonRecursiveTypes.Contains(field.FieldType))
            yield return field.Name;
        else
            foreach (var innerFieldName in GetFields(field.GetValue(obj)))
                yield return field.Name + "." + innerFieldName;
    }
}

推荐阅读