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.BinarySearchTree”中,无法将类型“DsLib.EnglishDictionaryWord”用作类型参数“T”。从“DsLib.EnglishDictionaryWord”到“System.IComparable”的隐式引用转换不存在。
如果我尝试进行
public class BinarySearchTree<T> : ICollection<T> where T : IComparable<T>
然后我遇到了这个编译错误,关于装箱转换不可用。
类型“T”无法用作泛型类型或方法“DsLib.BinaryTreeNode”的类型参数。从“T”到“System.IComparable”没有装箱转换或类型参数转换。
我有两个问题:
(1) 我对泛型实现感到困惑。有人能详细说明如何进行更正吗?以及避免将来出现此类错误的一般模式。何时使用,何时使用。
(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
... - Daniel Hilgarth