繁体   English   中英

VB.NET我应该为此使用集合吗?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM