递归泛型类型

lak*_*tak 21 c# generics

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

例如,我想定义一个Dictionary <>,它将其类型保存为TValue(用于层次结构).

Dictionary<string, Dictionary<string, Dictionary<string, [...]>>>
Run Code Online (Sandbox Code Playgroud)

Dan*_*ker 52

尝试:

class StringToDictionary : Dictionary<string, StringToDictionary> { }
Run Code Online (Sandbox Code Playgroud)

然后你可以写:

var stuff = new StringToDictionary
        {
            { "Fruit", new StringToDictionary
                {
                    { "Apple", null },
                    { "Banana", null },
                    { "Lemon", new StringToDictionary { { "Sharp", null } } }
                }
            },
        };
Run Code Online (Sandbox Code Playgroud)

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

  • lambda演算为胜利! (4认同)

ja7*_*a72 12

另一个例子是通用树

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; } }
}
Run Code Online (Sandbox Code Playgroud)

现在用它

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
}
Run Code Online (Sandbox Code Playgroud)

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