【发布时间】:2011-05-30 12:28:19
【问题描述】:
我有一个通用的 BST 和一个 dataItem 类来充当 treeNode 的值。
public class BinarySearchTree<T> : ICollection<T> where T : IComparable
{
}
public class EnglishDictionaryWord
: IComparer<EnglishDictionaryWord>, IComparable<EnglishDictionaryWord>
{
public EnglishDictionaryWord(string word, WordCompareType type)
{
Word = word;
Length = Word.Length;
_compareType = type;
}
public int Compare(EnglishDictionaryWord x, EnglishDictionaryWord y)
{
if (_compareType == WordCompareType.Length)
return new WordLengthComparer().Compare(x, y);
else if (_compareType == WordCompareType.Lexical)
return new WordLexicalComparer().Compare(x, y);
else
throw new InvalidOperationException("Unsupported Comparison type");
}
public int CompareTo(EnglishDictionaryWord obj)
{
return Compare(this, obj);
}
}
public class WordLengthComparer : IComparer<EnglishDictionaryWord>
{
public WordLengthComparer()
{
}
public int Compare(EnglishDictionaryWord x, EnglishDictionaryWord y)
{
return x.Length - y.Length;
}
}
and similar Lexical comparer class.
现在当我尝试使用时:
BinarySearchTree<EnglishDictionaryWord> _tree =
new BinarySearchTree<EnglishDictionaryWord>();
我得到编译错误:
类型“DsLib.EnglishDictionaryWord”不能用作泛型类型或方法“DsLib.BinarySearchTree”中的类型参数“T”。没有从“DsLib.EnglishDictionaryWord”到“System.IComparable”的隐式引用转换。
如果我尝试做
public class BinarySearchTree<T> : ICollection<T> where T : IComparable<T>
然后我得到这个关于装箱转换不可用的编译错误。
类型“T”不能用作泛型类型或方法“DsLib.BinaryTreeNode”中的类型参数“T”。没有从 'T' 到 'System.IComparable' 的装箱转换或类型参数转换。
我有两个问题:
(1)。
我对泛型实现感到困惑。有人可以详细说明如何纠正吗?和一般模式,以避免将来出现此类错误。
何时使用IComparable<T>,何时使用IComparable。
(2)。这个比较器模式是否正确,在数据项类中有比较器?因为用户将提供新的EnglishWord 插入到树中。他可能会为每个单词使用不同的比较器。然后它会破坏树。
编辑:添加 BSTNode 类代码
public class BinaryTreeNode<T> where T : IComparable
{
public BinaryTreeNode(T value)
{
Value = value;
}
public T Value { get; protected internal set; }
public BinaryTreeNode<T> Right { get; protected internal set; }
public BinaryTreeNode<T> Left { get; protected internal set; }
public BinaryTreeNode<T> Parent { get; protected internal set; }
public int Height { get; protected internal set; }
}
【问题讨论】:
-
我在任何地方都没有看到
DsLib.BinaryTreeNode... -
@Kamarey 我的问题是关于 IComparable 和 IComparable
而不是 IComparer 和 IComparable
标签: .net generics collections