我使用下面的代码创建的不是一个链表,而是一个generecic链表树。它工作得非常好。
public class Tree<T> where T : Tree<T>
{
T parent;
List<T> children;
public Tree(T parent)
{
this.parent = parent;
this.children = new List<T>();
if( parent!=null ) { parent.children.Add(this as T); }
}
public bool IsRoot { get { return parent == null; } }
public bool IsLeaf { get { return children.Count == 0; } }
}
力学示例用法(坐标系层次)
class Coord3 : Tree<Coord3>
{
Vector3 position;
Matrix3 rotation;
private Coord3() : this(Vector3.Zero, Matrix3.Identity) { }
private Coord3(Vector3 position, Matrix3 rotation) : base(null)
{
this.position = position;
this.rotation = rotation;
}
public Coord3(Coord3 parent, Vector3 position, Matrix3 rotation)
: base(parent)
{
this.position = position;
this.rotation = rotation;
}
public static readonly Coord3 World = new Coord3();
public Coord3 ToGlobalCoordinate()
{
if( IsRoot )
{
return this;
} else {
Coord3 base_cs = parent.ToGlobalCoordinate();
Vector3 global_pos =
base_cs.position + base_cs.rotation * this.position;
Matrix3 global_rot = base_cs.rotation * this.rotation;
return new Coord3(global_pos, global_ori );
}
}
}
技巧是用初始化根对象
null
起源。记住你
不能
做
Coord3() : base(this) { }
.