了解C#的IComparable [英] Understanding C#'s IComparable

查看:154
本文介绍了了解C#的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 a where clause that tells the compiler that the actual TNode type must implement IComparable<TNode>. So, the compiler knows that the instanciated generic type has a CompareTo(...) method.
You can only instanciate BinaryTreeNode<...> with a type that fulfills that where 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆