大多数人在编写实现IComparable <T>的refence类型(类)时,使用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 = …Run Code Online (Sandbox Code Playgroud)