我有以下课程:
public abstract class CustomerBase { public long CustomerNumber { get; set; } public string Name { get; set; } } public abstract class CustomerWithChildern: CustomerBase where T: CustomerBase { public IList Childern { get; private set; } public CustomerWithChildern() { Childern = new List (); } } public class SalesOffice : CustomerWithChildern { }
SalesOffice只是代表不同级别的客户层次结构的少数类之一.现在我需要从某个角度(CustomerBase)遍历这个层次结构.我不知道如何在不使用反射的情况下实现.我想实现类似的东西:
public void WalkHierarchy(CustomerBase start) { Print(start.CustomerNumber); if (start is CustomerWithChildern<>) { foreach(ch in start.Childern) { WalkHierarchy(ch); } } }
我有没有机会得到这样的工作?
基于我实现的has-childern接口的解决方案:
public interface ICustomerWithChildern { IEnumerable ChildernEnum { get; } } public abstract class CustomerWithChildern: CustomerBase, ICustomerWithChildern where T: CustomerBase { public IEnumerable ChildernEnum { get { return Childern; } } public IList Childern { get; private set; } public CustomerWithChildern() { Childern = new List (); } } 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); } } }
John Saunder.. 7
您可以将WalkHierarchy方法移动到基类并使其成为虚拟.基类实现只处理当前节点.对于CustomerWithChildern
班级,覆盖将进行实际行走.
您可以将WalkHierarchy方法移动到基类并使其成为虚拟.基类实现只处理当前节点.对于CustomerWithChildern
班级,覆盖将进行实际行走.