泛型和实现 IComparable
我对泛型非常陌生,我正在尝试编写一个简单的类,它将是泛型的,但也允许对字符串成员变量的一些描述进行排序。
目前我有一个基本类,但是当我尝试实现接口成员 CompareTo() 时,我在顶部收到一个错误,告诉我它尚未实现。这里有什么问题呢?
using System;
namespace GenericsPracticeConsole.Types
{
class SortableGenericType<T> : IComparable
{
private T t;
private string stringName;
public T name
{
get { return t; }
set { t = value; }
}
public int CompareTo(SortableGenericType<T> ourObject)
{
return stringName.CompareTo(ourObject.stringName);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

有两个接口
IComparable
和IComparable
。IComparable
是较旧的(出现在泛型之前),它需要将实例与任意对象进行比较。IComparable
要求将实例与U
的实例进行比较。如果您想声明将在 stringName 字段上比较 SortableGenericType 的实例,那么您应该这样做:如果您还想实现 IComparable:
如果您的类是一个将保存类型
T 并且您需要这些商品可订购(这不是您所要求的,但这是最常见的情况),而不是要求
T
为IComparable
:There are two interfaces
IComparable
andIComparable<U>
.IComparable
is the older one (that came before generics) which requires instances to be compared with arbitrary objects.IComparable<U>
requires instances to be compared with instances ofU
. If you want to declare that you will compare instances of SortableGenericType on stringName fields this is what you should do:If you also want to implement IComparable:
If your class was a collection that is going to hold items of type
T
and you needed those items to be orderable (this is not what you ask but it is the most common scenario) than you would requireT
to beIComparable<T>
: