2011-11-11 80 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 
相關問題