mardi 23 avril 2019

How do I recursively and reflectively get a list of all possible field name paths?

I am trying to get a collection of string that give me the names of the fields of all my class members, separated by .s. For example:

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;
    }
}

I believe some sort of recursion and reflection are required, but after writing dysfunctional code for hours, I need some help.

The reason I need this, is because I am accessing third party code which uses these file paths as the key to their respective values.

An example of one failed attempt:

    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;
    }

I have found several related questions, but none of them exactly fit my question, and I was unable to make the jump myself: Recursively Get Properties & Child Properties Of A Class, https://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: list the fields of a field that, itself, has fields





Aucun commentaire:

Enregistrer un commentaire