大多数人在编写实现 IComparable<T> 的引用类型(类)时,使用的约定是 null 比任何实际对象都少。但是如果你尝试使用相反的约定,就会发生一些有趣的事情:
using System;
using System.Collections.Generic;
namespace SortingNulls
{
internal class Child : IComparable<Child>
{
public int Age;
public string Name;
public int CompareTo(Child other)
{
if (other == null)
return -1; // what's your problem?
return this.Age.CompareTo(other.Age);
}
public override string ToString()
{
return string.Format("{0} ({1} years)", this.Name, this.Age);
}
}
internal static class Program
{
private static void Main()
{
var listOfChilds = new List<Child>
{
null,
null,
null,
null,
new Child { Age = 5, Name = "Joe" },
new Child { Age = 6, Name = "Sam" },
new Child { Age = 3, Name = "Jude" },
new Child { Age = 7, Name = "Mary" },
null,
null,
null,
null,
new Child { Age = 7, Name = "Pete" },
null,
new Child { Age = 3, Name = "Bob" },
new Child { Age = 4, Name = "Tim" },
null,
null,
};
listOfChilds.Sort();
Console.WriteLine("Sorted list begins here");
for (int i = 0; i < listOfChilds.Count; ++i)
Console.WriteLine("{0,2}: {1}", i, listOfChilds[i]);
Console.WriteLine("Sorted list ends here");
}
}
}
运行上述代码时,您会看到空引用未按预期排序。显然,A 和 B 比较时,如果 A 为对象且 B 为空,则使用用户定义的比较,但反之,如果 A 为空且 B 为对象,则使用一些 BCL 比较。
这是一个错误吗?