大多數人在編寫實現IComparable <T>的申請類型(類)時,使用null比任何實際對象都少的約定。但是,如果你嘗試使用相反的協定,一些有趣的事情發生了:排序其中一些爲空的IComparable對象
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是null,則使用用戶定義的比較,但是如果相反地A是空且B是對象,則使用一些BCL比較來替代。
這是一個錯誤?
很好的答案。我沒有注意到文檔說一個對象必須比null大。 當A爲空且B不爲空時,框架*可以*交換A和B,稱爲我的方法,然後翻轉返回的Int32的符號。我認爲有時會發生在舊的非通用IComparable中。 當然,使用IComparer或比較委託,很容易處理null作爲第一個參數。 –
JeppeSN
2011-05-31 16:28:59