If you are ok with reflection, you could make a class (see note below) with 
methods for the different types:
   public void DoElement(XMLElement elem) {...}
   public void DoText(XMLText text) {...}
   public void DoAttribute(XMLAttribute attr) {...}
and use reflection to build a list of Type / MethodInfo pairs.  (You'd go 
through all
the class's MethodInfo values, and get the datatype of the first parameter.)  
Then
you could iterate through that structure and use thisMethodInfo.Invoke to call 
the
first method where the node you're processing is an instance of the parameter
type associated with that method.

You could also implement a "late-bound" visitor using a registry of
type-to-processor-method mappings. Using such a registry, you could
run the following code:

class Node {
}

class BinaryNode : Node {
}

class SetNode : Node {
}

class Program {
 static void ProcessBinaryNode(BinaryNode n) {
   Console.WriteLine("Binary!");
 }

 static void ProcessSetNode(SetNode n) {
   Console.WriteLine("Set!");
 }

 static void Main(string[] args) {
   ProcessorRegistry registry = new ProcessorRegistry();
   registry.RegisterProcessor<BinaryNode>(ProcessBinaryNode);
   registry.RegisterProcessor<SetNode>(ProcessSetNode);

   Node n1 = new BinaryNode();
   Node n2 = new SetNode();

   registry.Process(n1);
   registry.Process(n2);
 }
}

And it would output:
Binary!
Set!

My first sketch of such a registry looks as follows:
public delegate void Processor<T>(T element);

public class ProcessorRegistry {
 private delegate void GeneralProcessor(object element);

 private Dictionary<Type, GeneralProcessor> processors = new
Dictionary<Type, GeneralProcessor>();

 public void RegisterProcessor<T>(Processor<T> processor) {
   processors.Add(typeof(T), delegate(object o) {
     processor((T)o);
   });
 }

 public void Process(object o) {
   processors[o.GetType()](o);
 }
}

(Can probably be improved.)

Regards,
Fabian

===================================
This list is hosted by DevelopMentorĀ®  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com

Reply via email to