2011-11-11 30 views
1

在下面的代码中,我在行If (Not hash.Add(Numbers(Num))) Then上收到以下错误类型'Integer'的值无法转换为'System.Array' 。我究竟做错了什么?VB.NET:无法将类型'Integer'的值转换为'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 
+1

除了当前的错误(这@shahkalpesh已经回答了),这是不可能的,你要使用'号(NUM)'在调用'Add',因为'Num'已经是一个值提取来自'Numbers'数组。 –

回答

2

里面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 
+0

由于在循环过程中他试图添加到散列集中,仍然会产生索引超出界限的错误 – Jay

+0

@D ..:编辑是在添加上述注释时完成的。 – shahkalpesh

0

您已经声明hashHashSet(Of Array),这意味着其持有的阵列。但是你试图向它添加整数。

您需要更改其声明(HashSet(Of Integer))或将呼叫更改为AddAdd(Numbers))。

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

1

您已创建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 

我希望你知道,它仅会发现第一个重复,并没有返回值任何类型,如果它没有找到重复。

0

这是你的意思吗?

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 
相关问题