I'm writing a small data structures library in C#, and I'm running into an architectural problem. Essentially I have a class which implements the visitor pattern, and there are many possible implementations of visitors:
public interface ITreeVisitor<T, U>
{
U Visit(Nil<T> s);
U Visit(Node<T> s);
}
public abstract class Tree<T> : IEnumerable<T>
{
public readonly static Tree<T> empty = new Nil<T>();
public abstract U Accept<U>(ITreeVisitor<T, U> visitor);
}
public sealed class Nil<T> : Tree<T>
{
public override U Accept<U>(ITreeVisitor<T, U> visitor) { return visitor.Visit(this); }
}
public sealed class Node<T> : Tree<T>
{
public Tree<T> Left { get; set; }
public T Value { get; set; }
public Tree<T> Right { get; set; }
public override U Accept<U>(ITreeVisitor<T, U> visitor) { return visitor.Visit(this); }
}
Anytime I want to pass in a visitor, I have to create a visitor class, implement the interface, and pass it in like this:
class InsertVisitor<T> : ITreeVisitor<T, Tree<T>> where T : IComparable<T>
{
public T v { get; set; };
public Tree<T> Visit(Nil<T> s)
{
return new Node<T>() { Left = Tree<T>.empty, Value = v, Right = Tree<T>.empty };
}
public Tree<T> Visit(Node<T> s)
{
switch (v.CompareTo(s.Value))
{
case -1: return new Node<T>() { Left = Insert(v, s.Left), Value = s.Value, Right = s.Right };
case 1: return new Node<T>() { Left = s.Left, Value = s.Value, Right = Insert(v, s.Right) };
default: return s;
}
}
}
public static Tree<T> Insert<T>(T value, Tree<T> tree) where T : IComparable<T>
{
return tree.Accept<Tree<T>>(new InsertVisitor<T>() { v = value });
}
I don't like writing that much boilerplate code, because it gets very messy when you have a non-trivial number of visitor implementations.
I want to write something similar to anonymous classes Java (concept code):
public static Tree<T> Insert<T>(T v, Tree<T> tree) where T : IComparable<T>
{
return tree.Accept<Tree<T>>(new InsertVisitor<T>()
{
public Tree<T> Visit(Nil<T> s) { return new Node<T>() { Left = Tree<T>.empty, Value = v, Right = Tree<T>.empty }; }
public Tree<T> Visit(Node<T> s)
{
switch (v.CompareTo(s.Value))
{
case -1: return new Node<T>() { Left = Insert(v, s.Left), Value = s.Value, Right = s.Right };
case 1: return new Node<T>() { Left = s.Left, Value = s.Value, Right = Insert(v, s.Right) };
default: return s;
}
}
};
}
Is there any way to simulate anonymous classes with interface implementations in C#?