开发者

Can I compare two arbitrary references in a way that can be used in a CompareTo method?

I'm writing an implementation of IComparable<T>.CompareTo(T) for a开发者_如何学C struct. I'm doing a member-wise comparison (i.e. d = a.CompareTo(other.a); if (d != 0) { return d; } etc.), but one of the members is of a class (let's call it Y) that doesn't implement IComparable or have any other reasonable way of comparing so I just want to compare the references (in this case I know that all instances of Y are unique). Is there a way of doing that that will yield an int that is suitable for use in a comparison method?


It's not meaningful to compare references looking for order relationships. It's only meaningful to look for equality.


Your statement that the class

doesn't implement IComparable or have any other reasonable way of comparing

Seems to be contra-indicative of finding

a way of doing that that will yield an int that is suitable for use in a comparison method

If the objects cannot be reasonably compared for ordering, it is best to exclude them from the comparison logic entirely.


Comparing the results of Object.GetHashCode() works well enough for my purposes (I just care about reference equality and it doesn't matter where anything unequal is sorted. I want instances of T that have the same instances of Y as members to be next to each other in the sorted result). My T.CompareTo() uses the following helper:

    static int Compare(object a, object b)
    {
        if (a == null)
        {
            return b == null ? 0 : 1;
        }
        if (b == null)
        {
            return -1;
        }
        return a.GetHashCode().CompareTo(b.GetHashCode());
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜