Click here to Skip to main content
15,896,409 members
Articles / General Programming / Algorithms

Polymorphic Extension Visitor with C#

Rate me:
Please Sign up or sign in to vote.
4.45/5 (7 votes)
26 Sep 2010CPOL1 min read 35.6K   174   13  
.NET 4 finally allows to define polymorphic extension visitors
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DynamicVisitor
{
    /// <summary>base visitor</summary>
    public class BaseVisitor: VisitorExtension.Visitor
    {
        #region construction and basic framework
        /// <summary>Constructor: the visitor calls Fallback if no matchin Visit method is found.</summary>
        public BaseVisitor()
            : base(false)
        {
        }

        // generic fall back if no visit method is found
        public override void Fallback(object objItem, Exception excException)
        {
            Console.WriteLine("{0}.Fallback({1}, {2})", this.GetType().Name, objItem.GetType().Name, excException.GetType().Name);
        }
        #endregion

        #region User defined Visit methods
        // visit method implementations
        public virtual void Visit(Base objItem)
        {
            Console.WriteLine("BaseVisitor.Visit<Base>({0})", objItem.GetType().Name);
        }
        public virtual void Visit(Derived_A objItem)
        {
            Console.WriteLine("BaseVisitor.Visit<Derived_A>({0})", objItem.GetType().Name);
        }
        #endregion
    }

    /// <summary>specific visitor</summary>
    public class SpecificVisitor : BaseVisitor
    {
        // visit all elements and call the Extension method Accept which calls polymorphically the appropriate Visit method.
        virtual public void Visit(Container objItem)
        {
            Console.WriteLine("SpecificVisitor.Visit<Container>({0})", objItem.GetType().Name);
            foreach (var objElement in objItem.Elements)
            {
                objElement.Accept(this);
            }
        }
    }

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder eXternSoft GmbH
Switzerland Switzerland
I feel comfortable on a variety of systems (UNIX, Windows, cross-compiled embedded systems, etc.) in a variety of languages, environments, and tools.
I have a particular affinity to computer language analysis, testing, as well as quality management.

More information about what I do for a living can be found at my LinkedIn Profile and on my company's web page (German only).

Comments and Discussions