I can work through the hierarchy with reflection, yes, but it is challenging, because the elements are diverse. So:
class A
{
string Hello;
}
class B
{
List<A> Hellos;
}
class E
{
A OtherRandomness;
}
class D:B
{
E randomthing;
}
class C:D
{
string OtherThing;
}
I have an object that is of type C, and I want to be able to find and identify that this has, down the line, a list of A object, and then to process them.
The real life example is a more complex hierarchy than this, of course, but the principle is the same. I have tried a recursive loop through the properties, but I was struggling to find ways of dealing with a) not trying to process string and int objects and b) identifying that a property was something like an enumerable of X. Related is the fact that there might be enumerables of classes that inherit from A.
If anyone can suggest an approach that would make this straightforward, that would be appreciated. I need to be able to do this in a range of places, so I have to be able to start with any class type.
So I start with a type of x. In this case x is C, but x could just as easily be Z, with no links to type A.
Also, this needs to pick up whether I have class D in or not. I want to be able to pick up Hellos and randomthing.
I assume that these are public instance properties. If you want something else, you can adapt the
BindingFlags.The idea of my solution is to test whether the type of the property is generic. If yes, it tests whether one of the type arguments is
typeof(A). However, It does not test nested generic types likeList<List<A>>. This would require a recursive approach.prints:
More specifically testing for enumerations of A using this type hierarchy:
Test:
prints:
It might be surprising that this returns lists of
AAas well. It happens because of theoutkeyword in the declaration of the interfaceIEnumerable<out T>making it covariant.This will, however, not include, e.g.
Dictionary<int,A>, because the dictionary implementsIEnumerable<KeyValuePair<int,A>>. My first solution would return such a property, but then it would require more work to get dictionary entries.