jeudi 17 septembre 2020

Find all instances of Type in an object graph

Lets say i have the following object graph

Parent : BaseEntity
  string1 SimpleString
  Middle Middle
  List<Child> Children (3)

Middle : BaseEntity
  string NormalStr
  int NiceInt
  RandomClass Ignore

 Child : BaseEntity
   string ChildString
   Parent Parent
  

In this example i want a way to give my Parent as input and get back a flat list {Parent, Middle, Child1, Child2, Child3}. It should work for any type of object graph.

Im trying to get there with reflection and recursion. The problem i run into is the cyclic reference between Parent and Child and i end up in an infinite loop.

How do i prevent this? I cant seem to get any "already seen" mechanism to work.

This is what i got so far. It works without the collection part, but that part is pretty important...

    public void TraverseThroughProperties(object myObject)
    {
        foreach (var prop in myObject.GetType().GetProperties())
        {
            var instance = prop.GetValue(myObject);
            if (instance is BaseEntity myBase)
                TraverseThroughProperties(instance);


            if (instance is ICollection collection)
            {
                foreach (var item in collection.OfType<BaseEntity>())
                    TraverseThroughProperties(item);
            }

            // Do something with myObject + prop
        }
    }




Aucun commentaire:

Enregistrer un commentaire