了解C#的IComparable [英] Understanding C#'s IComparable
问题描述
大家好,
到目前为止,我无法理解,对于以下实施,这是如何工作的......我不是用的东西,它来自我正在阅读的书。
Hello everyone,
So far I couldn't understand how, for the following implementation, this works... BIt is not something that I am using, it is from a book I am reading.
class BinaryTreeNode<TNode> : IComparable<TNode> where TNode : IComparable<TNode>
{
public BinaryTreeNode(TNode value) { Value = value; }
public BinaryTreeNode<TNode> Left { get; set; }
public BinaryTreeNode<TNode> Right { get; set; }
public TNode Value { get; private set; }
public int CompareTo(TNode other)
{
return Value.CompareTo(other);
}
}
为什么/ Value如何在调用CompareTo()时知道该怎么做和BinaryTreeNode< tnode>必须定义吗?
我用原始类型测试它工作正常,但是使用Object Class或我的一些类,它显示这个参数类型不在边界内。为什么会这样?如何解决?
问候,
Why/How does "Value" knows what to do when you call CompareTo() and "BinaryTreeNode<tnode>" must have it defined?
I tested with primitive type and it works fine, but with the Object Class or some of my classes, it shows "this argument type is not within bounds". Why does it happen? How to fix it?
Regards,
推荐答案
通用定义有where
子句告诉编译器实际的TNode
类型必须实现IComparable< TNode>
。因此,编译器知道instanciated泛型类型有一个CompareTo(...)
方法。
你只能实现BinaryTreeNode< ...>
,其类型符合,其中
约束。例如。string
履行该约束。请参阅 http://msdn.microsoft.com/en-us/library/system.string.aspx [ ^ ] :
The generic definition has awhere
clause that tells the compiler that the actualTNode
type must implementIComparable<TNode>
. So, the compiler knows that the instanciated generic type has aCompareTo(...)
method.
You can only instanciateBinaryTreeNode<...>
with a type that fulfills thatwhere
constraint. E.g.string
fulfills that constraint. See http://msdn.microsoft.com/en-us/library/system.string.aspx[^]:
[SerializableAttribute]
[ComVisibleAttribute(true)]
public sealed class String : IComparable,
ICloneable, IConvertible, IComparable<string>, IEnumerable<char>,
IEnumerable, IEquatable<string>
干杯
Andi
Cheers
Andi
这篇关于了解C#的IComparable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!