0

在 Comparer 类中比较函数的文档中,它说:

如果 a 实现了 IComparable,则 a。返回 CompareTo (b);否则,如果 b 实现 IComparable,则 b 的否定结果。返回 CompareTo (a)。

但是当我测试它时,它似乎会要求第一个输入实现 Icomparable。以下代码将产生错误:

class Program
{
    static void Main(string[] args)
    {
        Test t1 = new Test();
        Test2 t2 = new Test2();

        int i = Comparer.Default.Compare(t1,t2);

    }
}

class Test
{
}

class Test2 : IComparable
{
    public int CompareTo(object obj)
    {
        return 0;
    }
}

只是我还是文档错了?

4

1 回答 1

2

Refector 说它只检查 a 是否实现了 IComparable。

public int Compare(object a, object b)
{
if (a == b)
{
    return 0;
}
if (a == null)
{
    return -1;
}
if (b == null)
{
    return 1;
}
if (this.m_compareInfo != null)
{
    string str = a as string;
    string str2 = b as string;
    if ((str != null) && (str2 != null))
    {
        return this.m_compareInfo.Compare(str, str2);
    }
}
IComparable comparable = a as IComparable;
if (comparable == null)
{
    throw new ArgumentException(Environment.GetResourceString("Argument_ImplementIComparable"));
}
return comparable.CompareTo(b);

}

于 2009-10-19T12:57:36.440 回答