排序IComparable的对象,其中一些是空的 [英] Sorting IComparable objects some of which are null
问题描述
大多数人,当写refence类型(类),它实现IComparable的< T&GT ;,使用空比任何实际对象较少约定。但是,如果你尝试用相反的约定,一些有趣的事情发生了:
Most people, when writing a refence type (class) which implements IComparable<T>, use the convention that null is LESS than any actual object. But if you try to use the opposite convention, something interesting happens:
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");
}
}
}
在运行上面的code,你看到的空引用不排序预期。显然,相比较A到B的时候,如果A是一个对象,B是零,用户自定义的比较时,但如果反过来A是零,B是一个对象,一些BCL对比来代替。
When running the above code, you see that the null references are not sorted as expected. Apparently, when comparing A to B, if A is an object and B is null, the user-defined comparision is used, but if conversely A is null and B is an object, some BCL comparision is used instead.
这是一个错误?
推荐答案
没有,这是不是一个错误。你的的CompareTo
方法,它实现 IComparable的&LT;儿童&GT;
是在儿童定义
类。换句话说,如果你有才能做一个比较你的类型之一调用一个方法。
No, this is not a bug. Your CompareTo
method which implements IComparable<Child>
is defined on your Child
class. In other words, if you have to invoke a method on one of your types in order to make a comparison.
如果的孩子
项目之一,被比较是空,你怎么可以调用的CompareTo
就可以了?
If one of the Child
items being compared is null, how can you invoke CompareTo
on it?
请注意,从<一个定义href="http://msdn.microsoft.com/en-us/library/system.icomparable.compareto.aspx">IComparable:
根据定义,任何物体比较大于(或以下)空引用(在Visual Basic中为Nothing),和两个空引用比较彼此相等。的
这也解释了结果,你观察到。
Which explains the results you observe.
解决的办法是委托给一些其他的类来进行比较。请参阅<一href="http://msdn.microsoft.com/en-us/library/system.collections.icomparer.compare.aspx">IComparer接口。
The solution is to delegate to some other class to perform the comparison. See the IComparer interface.
这篇关于排序IComparable的对象,其中一些是空的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!