如果我理解正确,IComparable
和IComparable<T>
旨在允许一个自然人或总订货超过一组类型的定义。在任一情况下,通过CompareTo(Object)
或CompareTo(T)
定义的关系必须是自反,对称,和传递。可修改的IComparable实现?
当应用于单一类型或类型甚至是整个体系(假设那些更多派生类型不需要影响关系的定义),这一切都非常好,很好,非常适用。然而,一旦一个亚型引入状态应影响其在其从中衍生的那些类型方面的关系的元素,可比较的接口几乎似乎分解。
所提供的代码示例演示了我目前的解决问题的办法。因为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);
}
我认为这将是一个很好的代码审查网站的候选人。 – Brannon 2012-08-04 04:58:31