views:

46

answers:

2

EDIT: It looks like their is no simpler way to do this. Given the size of the class structure, the foreach approach seems to be the easiest (and probably the best) way to achieve my goal. I leave the question opened just in case someone has a brilliant idea. :)


Hi all,

I have a list of classes with a structure similar to this:

class A 
{
    ...
}

class B 
{
    ...

    public List<A> ListOfA {...}
}

class C 
{
    ...

    public List<A> ListOfA {...}
    public List<B> ListOfB {...}
}

class D 
{
    ...

    public List<A> ListOfA {...}
    public List<B> ListOfB {...}
    public List<C> ListOfC {...}
}

[...]

I need to create a method in the outer-most class (D in that case), that would have the following signature:

public IEnumerable<A> GetListOfA();

It would recursively (yield) return the list of instances of A contained in an instance of D.

The current implementation is a list of hard-coded foreach's. I'd like to make thing a little more flexible by dynamically looking through the properties of each class and subclass.

Just to give you some more details, the class structure is created from the FxCop XML report. The FxCop messages can be linked to a namespace, a module, a type, a member, etc. The XML is deserialized into this class structure and the messages can be found at different levels of the structure.

What I want to achieve is actually the equivalent of XPath //A over a class structure.

Would you have an idea on how implement such a method?

Thank you very much for your help

A: 

I think you should not try, if you want to achieve this ability I suggest you to maintain a collection of all A's in D, that will observe all of you child members, and the child will observe their childes and so on.

Chen Kinnrot
+1  A: 

You could use reflection to check if a method or property of a specific type exists (Type.GetMethods ...) or if a method with a specific return type exists.

testalino
I think your approach is right, after some thought and a few tests I ended up leaving the bunch of foreach as they are right now. Recursive reflection would be way too complex for no benefit. I was expecting to have missed an obviously simple way to do it. Thank you
Johann Blais