【发布时间】:2012-08-04 14:38:35
【问题描述】:
如果我理解正确,IComparable 和IComparable<T> 旨在允许定义一组类型的自然排序或全排序。无论哪种情况,CompareTo(Object) 或 CompareTo(T) 定义的关系都必须是Reflexive、Symmetric和Transitive。
当应用于单个类型甚至整个类型层次结构时,这一切都非常好,非常适用(假设那些更多派生的类型不需要影响关系的定义)。然而,一旦一个子类型引入了一个状态元素,该元素应该会影响它与其派生的那些类型之间的关系,那么可比较的接口似乎就会崩溃。
提供的代码示例演示了我当前对该问题的解决方案。因为RelationalObject 无法了解实际需要比较的那些类型,其预期目的主要是提供和密封CompareTo 的可修改实现,同时要求派生类型实际实现基于上下文的比较算法。
我想知道,有没有更好的方法来处理这种情况?我意识到我可能只需要实现一些IComparer 或IComparer<T>,它们知道并且可以处理已知对象的比较;然而,这似乎违背了IComparable 和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);
}
【问题讨论】:
-
我认为这将是 Code Review 网站的不错候选者。
标签: c# overriding compareto icomparable