Array.IndexOf始终返回-1

时间:2013-05-31 12:04:34

标签: asp.net arrays vb.net

这是我的代码。

Public Sub SomeFucntion(ByVal test As Short) 
    SomeOtherFucntion(MyArray)

    If Array.IndexOf(MyArray, test) <> -1
       //....
    End If
End Sub

测试返回值10.

但我的IndexOf值为-1 在QuickWatch内的VS 2005内,当我将值设为10而不是测试时,我得到了正确的index

我的数组是单维数组,现在有2.5和10.因为它得到10,理想情况下应该返回2作为索引。

2 个答案:

答案 0 :(得分:3)

Dim test As Short = 5

Dim MyArray() As Short = {1, 3, 4, 5, 7, 3}
If Array.IndexOf(MyArray, test) <> -1 Then
    MessageBox.Show("Index Found.") 
End If

以上作品。因为test被声明为short,所以请确保MyArray也被声明为short。

答案 1 :(得分:2)

问题可能是由于您的数组包含整数这一事实,但您要查找的值是。请考虑以下示例:

Dim myArray As Integer() = {5}
Dim value As Short = 5
Console.WriteLine(Array.IndexOf(myArray, value))  ' Prints -1

如果数组包含整数,则需要先将short转换为整数,例如,使用CInt

Dim myArray As Integer() = {5}
Dim value As Short = 5
Console.WriteLine(Array.IndexOf(myArray, CInt(value)))  ' Prints 0

编辑:请注意,声明的类型与此无关。让我们将数组声明为 Object ,因为这是您在评论中提到的内容(请注意,以下示例要求Option Strict Off,这很糟糕):

Dim myArray As Object = New Integer() {5}
Dim value As Object = 5S  ' Short literal
Console.WriteLine(Array.IndexOf(myArray, value))  ' still returns -1
Console.WriteLine(Array.IndexOf(myArray, CInt(value)))  ' returns 0

注意:您可以通过将函数声明为Public Sub SomeFunction(ByVal test As Integer)来隐式转换。