在Comparer类的比较函数文档中,它说:
如果一个实现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;
}
}
这只是我还是文档错了?
答案 0 :(得分:2)
Refector说它仅检查实现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);
}