public void ReflectiveVisit(VisitorElement element) { // Use reflection to find and invoke the correct Visit method Type[] types = new Type[] { element.GetType() }; MethodInfo methodInfo = this.GetType().GetMethod("Visit", types); if (methodInfo != null) methodInfo.Invoke(this, new object[] { element }); else Console.WriteLine("Unexpected Visit"); }
static void Main() { // Set up the object structure VisitorElement objectStructure = new VisitorElement( new VisitorElement( new ElementWithLink( new VisitorElement( new VisitorElement( new ElementWithLink( new VisitorElement(null), new VisitorElement( null)))), new VisitorElement( new VisitorElement( new VisitorElement(null)))))); Console.WriteLine("Count the elements"); CountVisitor visitor = new CountVisitor(); visitor.CountElements(objectStructure); Console.WriteLine("Number of Elements is: " + visitor.Count); }
// Only Elements are counted public void Visit(VisitorElement element) { Count++; }
public void CountElements(VisitorElement element) { ReflectiveVisit(element); if (element.Part != null) CountElements(element.Part); if (element.Next != null) CountElements(element.Next); }
public ElementWithLink(VisitorElement part, VisitorElement next) { Next = next; Part = part; }
public VisitorElement(VisitorElement next) { Next = next; }