我已经实现了以下分层数据结构:Tree<T> → Branch<T> → T。
更新:很多人问:为什么不使用对象而是使用<T>(或<dynamic>或其他)?所以我修改了我的问题来说明我的“约束条件”。我们开始吧...
这里有一些示例
C#的实现:
假设我有不同的树,我无法将它们放入列表中:
错误是:未找到隐式类型数组的最佳类型 如何从所有这些树中获取列表? 我想强调的是,我只想把它们放在一个列表中,可能会迭代它并访问当前树及其所有分支(例如,显示它们的名称)。我不关心T是对象还是抽象基类!假设我只调用
Tree
:*
├─Negative
│ ├─-2
├─0
│ ├─0
├─Positive
│ ├─2
│ ├─12
│ ├─2147483647
*
├─Spring
│ ├─Mar
│ ├─Apr
│ ├─May
├─Summer
│ ├─Jun
│ ├─Jul
│ ├─Aug
├─Fall
│ ├─Sep
│ ├─Oct
│ ├─Nov
├─Winter
│ ├─Dec
│ ├─Jan
│ ├─Feb
C#的实现:
public class Tree<T>
{
public readonly List<Branch<T>> Branches = new List<Branch<T>>();
}
public class Branch<T>
{
public readonly List<T> Leaves = new List<T>();
public string Name { get; set; }
}
public class StringLeaf
{
public StringLeaf(string value) { Label = value; }
public string Label { get; private set; }
public override string ToString() { return Label; }
}
public class PositiveIntLeaf
{
private readonly int _value;
public PositiveIntLeaf(int value) { _value = value; }
public string Value
{
get { return _value < 0 ? "-" : _value.ToString(); }
}
public override string ToString() { return Value; }
}
public class IntTree : Tree<IntLeaf>
{
private readonly Branch<IntLeaf> _negatives = new Branch<IntLeaf> { Name = "Negative" };
private readonly Branch<IntLeaf> _zeros = new Branch<IntLeaf> { Name = "0" };
private readonly Branch<IntLeaf> _positives = new Branch<IntLeaf> { Name = "Positive" };
public IntTree()
{
Branches.AddRange(new []{
_negatives,
_zeros,
_positives
});
}
public void Add(int value)
{
if (value < 0) _negatives.Leaves.Add(new IntLeaf(value));
else if (value > 0) _positives.Leaves.Add(new IntLeaf(value));
else _zeros.Leaves.Add(new IntLeaf(value));
}
}
假设我有不同的树,我无法将它们放入列表中:
IntTreeintTree = new IntTree();
intTree.Add(-2); intTree.Add(2); intTree.Add(0); intTree.Add(12); intTree.Add(int.MaxValue);
Tree<StringLeaf> months = new Tree<StringLeaf>{ Branches =
{
new Branch<StringLeaf> { Name = "Spring", Leaves = { new StringLeaf( "Mar"),new StringLeaf("Apr") ,new StringLeaf("May")} },
new Branch<StringLeaf> { Name = "Summer", Leaves = { new StringLeaf( "Jun"),new StringLeaf("Jul") ,new StringLeaf("Aug")} },
new Branch<StringLeaf> { Name = "Fall", Leaves = { new StringLeaf( "Sep"),new StringLeaf("Oct") ,new StringLeaf("Nov")} },
new Branch<StringLeaf> { Name = "Winter", Leaves = { new StringLeaf( "Dec"),new StringLeaf("Jan") ,new StringLeaf("Feb")} }
}};
var list = new [] { intTree, months };
var currentTree = list[0];
// Work with the current tree:
var count = currentTree.Branches.Count;
Display(currentTree);
错误是:未找到隐式类型数组的最佳类型 如何从所有这些树中获取列表? 我想强调的是,我只想把它们放在一个列表中,可能会迭代它并访问当前树及其所有分支(例如,显示它们的名称)。我不关心T是对象还是抽象基类!假设我只调用
.ToString()
。具体类型仅对于子类型(如IntTree
)很重要。