Vb.net BinarySearch-无法比较数组中的两个元素

Vb.net BinarySearch-无法比较数组中的两个元素,vb.net,.net-4.0,binary-search,invalidoperationexception,.net-1.1,Vb.net,.net 4.0,Binary Search,Invalidoperationexception,.net 1.1,因此,我们最近将一个应用程序从.NET1.1迁移到.NET4.0。 因此,我们必须解决一系列兼容性问题。 其中之一是一个代码块正在抛出InvalidOperationException 在我们迁移到.NET4之前,它在.NET1中正常工作。现在,根据我读到的一些线程,有一些关于这个问题的报告在.NET4.5中得到了修复。为了在我当前的版本中解决这个问题,我必须在数组的所有元素上实现IComparable接口 我该如何着手解决这个问题?我将感谢任何帮助和指点。谢谢 编辑:将链接添加到代码中使用的B

因此,我们最近将一个应用程序从.NET1.1迁移到.NET4.0。 因此,我们必须解决一系列兼容性问题。 其中之一是一个代码块正在抛出InvalidOperationException

在我们迁移到.NET4之前,它在.NET1中正常工作。现在,根据我读到的一些线程,有一些关于这个问题的报告在.NET4.5中得到了修复。为了在我当前的版本中解决这个问题,我必须在数组的所有元素上实现IComparable接口

我该如何着手解决这个问题?我将感谢任何帮助和指点。谢谢

编辑:将链接添加到代码中使用的BinarySearch方法

将实现添加到类定义中。2.将IComparable.CompareTo的方法添加到类中。借用msdn:

Public Class Temperature
    Implements IComparable
    ' The temperature value
    Protected temperatureF As Double

Public Overloads Function CompareTo(ByVal obj As Object) As Integer _
Implements IComparable.CompareTo

    If obj Is Nothing Then Return 1
    Dim otherTemperature As Temperature = TryCast(obj, Temperature)
    If otherTemperature IsNot Nothing Then
        Return Me.temperatureF.CompareTo(otherTemperature.temperatureF)
    Else
      Throw New ArgumentException("Object is not a Temperature")
    End If   
End Function

....

End Class
CompareTo函数中的代码的粗略程度取决于您没有提供多少内容的类。所有数字类型(如Int32和Double)都实现IComparable,String、Char和DateTime也是如此。自定义类型还应该提供自己的IComparable实现,以便能够对对象实例进行排序。我相信你的情况可能就是这样。我希望这能有所帮助。

试试这个:

   ...
   Array.Sort(Of Integer)(someNumber)  ' only if someNumber is not previously sorted
   If Array.BinarySearch(Of Integer)(someNumber, MyEnum.Something) >= 0 Then
     ...
   End If
...
这在所有.NET frameworks>2.0中都应该有效。

我该如何着手解决这个问题

您没有正确使用它。BinarySearch是一种共享/静态方法,在尝试将其用作实例方法时,不会在Intellisense中显示:

如果您仍然键入它,您将得到一个新的编译器警告:访问共享成员。。。通过一个实例。。。将不进行评估。MSDN没有任何关于NET1.1的内容,所以我不知道从那以后它是否发生了变化。正确用法:

IndexOf6 = Array.BinarySearch(myIntAry, 6)
这就引出了一个问题,作为从NET1.x到4.5转换的一部分,为什么不将其转换为ListofInt32呢。快速测试表明IndexOf方法的速度快2-3倍:

IndexOf6 = intList.IndexOf(6)

列表方法也更“独立”,因为与System.Array不同,它不需要排序才能工作。

我们可以看到进行比较的二进制搜索代码吗?它是System.Array中的内置函数。哪一个?我们需要更多信息来帮助您。BinarySearch是一种System.Array方法。someNumber.BinarySearchoptions,MyEnum.someone在技术上是无效的语句,但它将编译。BinarySearch是Array类中的一个共享静态方法。正确的语法是Array.BinarySearcharrayToSearch,itemToFind。如果选项是整数数组,则不需要提供IComparable,因为整数结构实现了该接口。
IndexOf6 = intList.IndexOf(6)