递归generics类型

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

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

Dictionary<string, Dictionary<string, Dictionary>> 

尝试:

 class StringToDictionary : Dictionary { } 

然后你可以写:

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

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

另一个例子是通用树

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