如何在执行Array.BinarySearch </t>时调用IComparable <t>

时间:2013-10-07 21:26:10

标签: c# .net arrays sorting

记录BinarySearch方法行为的MSDN page表明数组和被搜索的值都可以实现IComparable:

1)页面描述

  

valuearray的每个元素都必须实现IComparable   interface,用于比较。

2)此外,该方法抛出InvalidOperationException if

  

value未实现IComparable界面和搜索   遇到一个没有实现IComparable的元素   接口

我试图证明这种行为(使用值的IComparable接口)但是无法做到。这是我的代码:

// Declarations
class Many 
{
    public string data { get; set; }
}
class One : Many, IComparable<Many>
{
    public int CompareTo(Many other)
    {
        Console.WriteLine("Comparator of One invoked");
        if (this.data.Length < other.data.Length) return -1;
        if (this.data.Length > other.data.Length) return 1;
        return 0;
    }
}
...
// action
    Many[] manies = new[] { new Many { data = "1" }, 
                            new Many { data = "22" },  
                            new Many { data = "333" }, 
                            new Many { data = "4444" }, };
    One one = new One {data="333"};
    Console.WriteLine(Array.BinarySearch(manies, one));

当我运行此操作时,我会收到System.InvalidOperationException,如果value未实现IComparable,则应根据文档进行操作。但是在我看来它确实实现了IComparable

如何运行值的比较器而不是数组中的元素?

1 个答案:

答案 0 :(得分:2)

现在,我了解了这个问题,请更改One的实施,以实施IComparable而不是IComparable<Many>。查看文档,我认为这是缺少的组件。如果需要,您可以同时实现这两项,但Array.BinarySearch将不使用IComparable<T>接口。

此代码对我有用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestProject
{
    public class NoCompare
    {
        public string V
        {
            get;
            set;
        }
    }

    public class Compare : IComparable
    {
        public string V
        {
            get;
            set;
        }

        public int CompareTo(object obj)
        {
            NoCompare a = obj as NoCompare;

            if (a == null)
                return -1;

            return String.Compare(V, a.V);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            NoCompare[] strings = new NoCompare[] { new NoCompare() { V = "a" }, new NoCompare() { V = "b" }, new NoCompare() { V = "c" } };

            Compare t = new Compare();
            t.V = "b";

            Array.BinarySearch((object[])strings, t);
       }
    }
}