为了观察 System.Array.BinarySearch 中键的比较器的调用(与涉及调用数组元素的比较器的典型场景相反),我们设置了以下测试:
class Many
{
public string data { get; set; }
}
class One : Many, IComparable
{
public int CompareTo(object arg)
{
Many other = arg as Many;
Console.WriteLine("Comparator of One invoked from: " + this.data);
if (this.data.Length < other.data.Length) return -1;
if (this.data.Length > other.data.Length) return 1;
return 0;
}
}
当我运行以下命令时,使用这些新声明:
Many[] manies = new[] { new Many { data = "1" },
new Many { data = "22" },
new Many { data = "333" },
new Many { data = "4444" }, };
One one = new One {data="???"};
Console.WriteLine(Array.BinarySearch(manies, one));
我得到输出:
Unhandled Exception: System.InvalidOperationException: Failed to compare two elements in the array. ---> System.ArgumentException: At least one object must implement IComparable.
at System.Collections.Comparer.Compare(Object a, Object b)
at System.Collections.Generic.ObjectComparer`1.Compare(T x, T y)
at System.Collections.Generic.ArraySortHelper`1.InternalBinarySearch(T[] array, Int32 index, Int32 length, T value, IComparer`1 comparer)
at System.Collections.Generic.ArraySortHelper`1.BinarySearch(T[] array, Int32 index, Int32 length, T value, IComparer`1 comparer)
--- End of inner exception stack trace ---
at System.Collections.Generic.ArraySortHelper`1.BinarySearch(T[] array, Int32 index, Int32 length, T value, IComparer`1 comparer)
at System.Array.BinarySearch[T](T[] array, Int32 index, Int32 length, T value, IComparer`1 comparer)
at System.Array.BinarySearch[T](T[] array, T value)
at ConsoleApplication1.Prosram.Main(String[] args) in C:\Users\xxx\documents\visual studio 2010\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line xxx