【问题标题】:VB.NET: Value of Type 'Integer' cannot be converted to 'System.Array'VB.NET:“整数”类型的值无法转换为“System.Array”
【发布时间】:2011-11-11 15:23:04
【问题描述】:

在下面的代码中,我在行 If (Not hash.Add(Numbers(Num))) Then 上收到以下错误“整数”类型的值无法转换为“System.Array”。我做错了什么?

Module Module1

Sub Main()

    Dim array() As Integer = {5, 10, 12, 8, 8, 14}

    ' Pass array as argument.
    Console.WriteLine(findDup(array))

End Sub

Function findDup(ByVal Numbers() As Integer) As Integer

    Dim hash As HashSet(Of Array)

    For Each Num In Numbers

        If (Not hash.Add(Numbers(Num))) Then
            Return (Num)
        End If

    Next

End Function

End Module

【问题讨论】:

  • 除了当前错误(@shahkalpesh 已回答)之外,您不太可能在调用 Add 时使用 Numbers(Num),因为 Num 已经是从Numbers 数组。

标签: vb.net


【解决方案1】:

findDup里面,这个

Dim hash As HashSet(Of Array)

应该是

Dim hash As HashSet(Of Integer)

编辑:正如@Damien_The_Unbeliever 所建议的,代码

这一行

If (Not hash.Add(Numbers(Num))) Then

应该是

If (Not hash.Add(Num)) Then

【讨论】:

  • 仍然会产生一个 Index Out of Bounds 错误,因为他试图在循环期间添加到哈希集
  • @D..:编辑在您添加上述评论时完成。
【解决方案2】:

您创建了一个 Array 的哈希集,而不是一个 Integer 的哈希集。您可以将其更改为整数,并更改尝试在循环中添加内容的方式:

Function findDup(ByVal Numbers() As Integer) As Integer

    Dim hash As New HashSet(Of Integer)

    For Each Num In Numbers

        If (Not hash.Add(Num)) Then
            Return (Num)
        End If

    Next

End Function

我希望您意识到它只会找到第一个重复项,并且如果找不到重复项,则不会返回任何类型的值。

【讨论】:

    【解决方案3】:

    您已将 hash 声明为 HashSet(Of Array),这意味着它包含数组。但是您正在尝试向其添加整数。

    您需要更改其声明 (HashSet(Of Integer)) 或将调用更改为 Add (Add(Numbers))。

    您使用哪种解决方案取决于您的意图。我的猜测是你想改变hash的类型。

    【讨论】:

      【解决方案4】:

      这是你的意思吗?

      Sub Main()
      
          Dim someArray() As Integer = {5, 10, 12, 8, 7, 8, 8, 10, 14, 10}
      
          ' Pass array as argument.
          Dim foo As List(Of Integer) = findDups(someArray)
          'foo contains a list of items that have more than 1 occurence in the array
      End Sub
      
      Function findDups(ByVal Numbers() As Integer) As List(Of Integer)
          Dim rv As New List(Of Integer)
          For idx As Integer = 0 To Numbers.Length - 1
              If Array.LastIndexOf(Numbers, Numbers(idx)) <> idx Then
                  If Not rv.Contains(Numbers(idx)) Then rv.Add(Numbers(idx))
              End If
          Next
          Return rv
      End Function
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-14
        • 2022-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多