Curiously Recurring Template in C#

元ネタは「Faith and Brave - C++で遊ぼう」より『C#でCRTP』.
以前 arton さんのところ でも書きましたが,C# ですぐに思い付く例としては class Node<T> : List<Node<T>> による簡易ノードですかね.私が最初に見たのは XNA の SpaceWar サンプルでした.あれ以来私の中では『XNA チーム = .NET マニアの巣窟』という図式ができあがっています.



例えば型の継承ツリーをこんな感じで作ってみたり.

using System;
using System.Collections.Generic;
using System.Linq;

public sealed class Node<T> : List<Node<T>>
{
    public T NodeValue { get; set; }
}

static class Program
{
    static void Main(string[] args)
    {

        var typenodes = typeof(int).Assembly.GetTypes()
                          .Select(type => new Node<Type> { NodeValue = type })
                          .ToList();

        // update connections
        typenodes.ForEach(
            node => node.AddRange( from child in typenodes
                                   where child.NodeValue.BaseType == node.NodeValue
                                   select child) );

        foreach (var node in typenodes.Where(x => x.Count > 0))
        {
            Console.WriteLine("{0}'s children:", node.NodeValue);
            foreach (var child in node)
            {
                Console.WriteLine("\t{0}", child.NodeValue);
            }
        }
    }
}