如果我理解正确,IComparable
并且IComparable<T>
旨在允许在一组类型上定义自然或总排序。在任何一种情况下,由CompareTo(Object)
or定义的关系CompareTo(T)
必须是Reflexive、Symmetric和Transitive。
当应用于单个类型甚至整个类型层次结构时,这一切都非常好并且非常适用(假设那些更多派生的类型不需要影响关系的定义)。然而,一旦一个子类型引入了一个状态元素,该元素应该影响它与它派生的那些类型的关系,可比较的接口几乎似乎崩溃了。
提供的代码示例演示了我当前对该问题的解决方案。由于RelationalObject
无法了解实际需要比较的那些类型,其预期目的主要是提供和密封可修改的实现,CompareTo
同时要求派生类型实际实现基于上下文的比较算法。
我想知道,有没有更好的方法来处理这种情况?我意识到我可能只实现一些IComparer
或IComparer<T>
哪些知道并可以处理已知对象的比较;然而,这似乎违背了IComparable
and的目的IComparable<T>
。
using System;
public abstract class RelationalObject : IComparable<RelationalObject>
{
public sealed int CompareTo(RelationalObject that)
{
int relation = 0;
if (that == null)
relation = 1;
if (relation == 0 && !this.Equals(that))
{
Type thisType = this.GetType();
Type thatType = that.GetType();
if (thatType.IsInstanceOfType(this))
{
if (thisType.Equals(thatType))
relation = this.CompareToExactType(that);
else
relation = -1 * that.CompareToSuperType(this);
}
else
{
if (thisType.IsInstanceOfType(that))
relation = this.CompareToSuperType(that);
else
relation = this.CompareToForeignType(that);
}
}
return relation;
}
protected abstract int CompareToExactType(RelationalObject that);
protected abstract int CompareToForeignType(RelationalObject that);
protected abstract int CompareToSuperType(RelationalObject that);
}