I have following classes:
public abstract class CustomerBase { public long CustomerNumber { get; set; } public string Name { get; set; } } public abstract class CustomerWithChildern<T> : CustomerBase where T: CustomerBase { public IList<T> Childern { get; private set; } public CustomerWithChildern() { Childern = new List<T>(); } } public class SalesOffice : CustomerWithChildern<NationalNegotiation> { }
The SalesOffice is just one of few classes which represent different levels of customer hierarchy. Now I need to walk through this hierarchy from some point (CustomerBase). I can’t figure out how to implement without using reflection. I’d like to implement something like:
public void WalkHierarchy(CustomerBase start) { Print(start.CustomerNumber); if (start is CustomerWithChildern<>) { foreach(ch in start.Childern) { WalkHierarchy(ch); } } }
Is there any chance I could get something like this working?
The solution based on suggested has-childern interface I implemented:
public interface ICustomerWithChildern { IEnumerable ChildernEnum { get; } } public abstract class CustomerWithChildern<T> : CustomerBase, ICustomerWithChildern where T: CustomerBase { public IEnumerable ChildernEnum { get { return Childern; } } public IList<T> Childern { get; private set; } public CustomerWithChildern() { Childern = new List<T>(); } } public void WalkHierarchy(CustomerBase start) { var x = start.CustomerNumber; var c = start as ICustomerWithChildern; if (c != null) { foreach(var ch in c.ChildernEnum) { WalkHierarchy((CustomerBase)ch); } } }
I believe that you want to make the lookup for the determination of doing to the walk an interface.
So maybe add an ‘IWalkable’ interface that exposes the information needed to do the walk, then you can create your method checking to see if the passed object implements the interface.