我正在更新一些旧代码以使用SortedList(Of String,Integer)对象,而最低级别的函数突然开始抛出错误。当我开始通过解析的行枚举时,抛出“KeyNotFoundException”错误。代码如下:
Public Function GetFileToolList(ByVal EIAFilePath As String) As SortedList(Of String, Integer)
'Gets a full list of tools being used (and reused) in a GCode program
Dim tools As New SortedList(Of String, Integer)
Dim words() As String
For Each line As String In IO.File.ReadAllLines(EIAFilePath)
'Determine if line contains M6
If line.ToUpper.Contains("T") Then
If line.Contains("M06") Or line.Contains("M6") Then
'If line ends with M06(M6) or contains M06(M6) then parse string to extract tool number
' If line contains M06(M6) then parse to second tool number after M-Code
' Example: T120 M06 T121
' Changes from T120 to T121
words = line.Split(" ")
If Not IsNothing(words) Then
'THE FOLLOWING LINE THROWS KeyNotFoundException
For i = 0 To words.Length - 1 Step 1
If words(i).ToUpper.StartsWith("T") Then
If Not (i + 1) >= words.Length Then
If words(i + 1).ToUpper.Contains("M06") Or words(i + 1).ToUpper.Contains("M6") Then
'START OF UPDATED CODE**********************
If IsNothing(tools) Then
tools.Add(words(i).Remove(0, 1), 1)
Else
If Not tools.ContainsKey(words(i).Remove(0,1)) Then
tools.Add(words(i).Remove(0, 1), 1)
Else
tools(words(i).Remove(0, 1)) += 1
End If
End If
'END OF UPDATED CODE************************
Continue For
End If
End If
End If
Next
End If
End If
End If
Next
Return tools
End Function
我看到的关于此错误的所有线程都与Dictionary对象有关。我最接近的是“工具”SortedList对象,但异常是在String数组上抛出的。那么,如果您可以解释为什么在“单词”的枚举中发生异常,可能会导致此异常和奖励积分。提前谢谢!