递归泛型类型

时间:2009-03-15 09:18:36

标签: c# generics

是否可以在C#中定义引用自身的泛型类型?

E.g。我想定义一个Dictionary<>将其类型保存为TValue(用于层次结构)。

Dictionary<string, Dictionary<string, Dictionary<string, [...]>>>

2 个答案:

答案 0 :(得分:47)

尝试:

class StringToDictionary : Dictionary<string, StringToDictionary> { }

然后你可以写:

var stuff = new StringToDictionary
        {
            { "Fruit", new StringToDictionary
                {
                    { "Apple", null },
                    { "Banana", null },
                    { "Lemon", new StringToDictionary { { "Sharp", null } } }
                }
            },
        };

递归的一般原则:找到一些方法为递归模式命名,因此它可以通过名称引用它自己。

答案 1 :(得分:11)

另一个例子是通用树

public class Tree<T> where T : Tree<T>
{
    public T Parent { get; private set; }
    public List<T> Children { get; private set; }
    public Tree(T parent)
    {
        this.Parent = parent;
        this.Children = new List<T>();
        if(parent!=null) { parent.Children.Add(this); }
    }
    public bool IsRoot { get { return Parent == null; } }
    public bool IsLeaf { get { return Children.Count==0; } }
}

现在使用它

public class CoordSys : Tree<CoordSys>
{
    CoordSys() : base(null) { }
    CoordSys(CoordSys parent) : base(parent) { }
    public double LocalPosition { get; set; }
    public double GlobalPosition { get { return IsRoot?LocalPosition:Parent.GlobalPosition+LocalPosition; } }
    public static CoordSys NewRootCoordinate() { return new CoordSys(); }
    public CoordSys NewChildCoordinate(double localPos)
    {
        return new CoordSys(this) { LocalPosition = localPos };
    }
}

static void Main() 
{
    // Make a coordinate tree:
    //
    //                  +--[C:50] 
    // [A:0]---[B:100]--+         
    //                  +--[D:80] 
    //

    var A=CoordSys.NewRootCoordinate();
    var B=A.NewChildCoordinate(100);
    var C=B.NewChildCoordinate(50);
    var D=B.NewChildCoordinate(80);

    Debug.WriteLine(C.GlobalPosition); // 100+50 = 150
    Debug.WriteLine(D.GlobalPosition); // 100+80 = 180
}

请注意,您无法直接实例化Tree<T>。它必须是树中节点类的基类。想想class Node : Tree<Node> { }