[英]VB.NET Should I use a collection for this?
我正在嘗試將舊的VB6代碼引入現代VB.NET代碼。
在我的VB6代碼中,我需要查詢集合中是否存在鍵。
我這樣做是這樣的:
Private Function pIndexFromKey(ByRef uCol As Collection, ByVal uText As String) As Long
On Error Resume Next
Dim lRet&
lRet = uCol.Item(uText)
pIndexFromKey = lRet
End Function
如果pIndexFromKey返回0,則表示該鍵未包含在集合中,因此我將其添加為:
nCollection.Add(lIndex, sText)
我想知道這是否是“不錯”的方法。 我認為不是因為在.NET中我使用的是VisualBasic集合,而事實是它是“ VB”而不是系統集合,這使我感到懷疑。
僅作記錄,這是我的VB.NET代碼:
Private Function pIndexFromKey(ByRef uCol As Collection, ByVal uText As String) As Integer
On Error Resume Next
Dim lRet As Integer = CInt(uCol(uText))
Return lRet
End Function
代碼可以正常工作,但是我的On Error Resume Next方法看起來很丑陋,而且我不希望每次拋出(和吃掉)錯誤時都讓調試窗口告訴我有關異常的信息。
有人有更好的主意嗎?
您可以簡單地使用contains方法來檢查密鑰是否存在。
我不會使用“下一個錯誤恢復”方法。 只需使用“包含”方法測試集合。
Dim Ret as integer
Ret=0
If (uCol.contains(uText)) then
Ret= CInt(uCol(uText))
Return ret
刪除您的VB集合並使用高級通用列表。
在您的情況下,我懷疑您使用的是簡單的List(Of String)。
如果是這樣,請將此替代方法用於您的方法
Dim k as List(Of String) = new List(Of String)
k.Add("Test1")
k.Add("Test2")
k.Add("Test3")
k.Add("Test4")
k.Add("Test5")
' No need to use Contains, IndexOf doesn't throw exceptions if the element is not there
Dim x = k.IndexOf("Test4")
if x = -1 then
Console.WriteLine("Test4 is not in list")
else
Console.WriteLine("Test4 is at index" + x.ToString)
End if
您可以使用Generic.Dictionary (字符串,整數)。 所以代替這個:
Private Function pIndexFromKey(ByRef uCol As Collection, ByVal uText As String) As Integer
On Error Resume Next
Dim lRet As Integer = CInt(uCol(uText))
Return lRet
End Function
您將擁有:
Private Function pIndexFromKey(dict As Dictionary(Of String, Integer), uText As String) As Integer
Dim lRet As Integer
If dict.TryGetValue(uText, lRet) Then Return lRet
Return -1 'default value if key was not found in the dictionary
End Function
如果您擁有Vb.Net,則可以在“嘗試使用示例:嘗試”中處理錯誤。
異常捕獲
結束嘗試
我希望我能正確理解
對於初學者,我將VisualBasic.Collection
替換為ObjectModel.Collection(Of T)
。 然后,擺脫您的自定義函數,僅檢查Contains()
方法。
Dim nCollection As New ObjectModel.Collection(Of String)
Dim sText As String = "value"
If Not nCollection.Contains(sText) Then
nCollection.Add(uText)
End If
If nCollection.Contains(sText) Then
Dim index = nCollection.IndexOf(sText)
End If
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.