【发布时间】:2013-11-15 14:23:36
【问题描述】:
我已经实现了以下分层数据结构:Tree
更新:很多人问:为什么不使用 object 而不是
这里是示例Trees:
*
├─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 这样的子类型很重要。
【问题讨论】:
-
当您似乎想在一个集合中拥有不同的类型时,为什么在这种情况下使用泛型? ArrayList 或许就足够了?
-
这可能是一个毫无意义的评论,不知道你的约束,但如果在一天结束时你只是将它们捆绑在一起,失去所有类型,那么保持类的通用性有什么意义- 泛型提供的安全性?
-
阅读协方差
-
@decPL 现在有一点要保持类的通用性。我希望...