0

我正在更新一些旧代码以使用 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 对象,但异常是在字符串数组上引发的。那么,如果您可以通过枚举“单词”来解释为什么会发生异常,那么可能导致此异常和加分的原因是什么。提前致谢!

4

0 回答 0