递归泛型类型

问题描述 投票:0回答:2

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

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

Dictionary<string, Dictionary<string, Dictionary<string, [...]>>>
c# generics
2个回答
59
投票

尝试:

class StringToDictionary : Dictionary<string, StringToDictionary> { }

然后你可以写:

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

递归的一般原则:找到某种方法为递归模式命名,以便它可以通过名称引用自身。


20
投票

另一个例子是通用树

public class Tree<TDerived> where TDerived : Tree<TDerived>
{
    public TDerived Parent { get; private set; }
    public List<TDerived> Children { get; private set; }
    public Tree(TDerived parent)
    {
        this.Parent = parent;
        this.Children = new List<TDerived>();
        if(parent!=null) { parent.Children.Add((TDerived)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<TDerived>
。它必须是树中节点类的基类。想
class Node : Tree<Node> { }

© www.soinside.com 2019 - 2024. All rights reserved.