C#index超出范围String Array和List <string>

Nig*_*ce2 5 c# arrays

在尝试了一些错误检查方法后,我得出结论,我需要帮助解决这个问题.

我怎么没有发现这个"索引超出范围"的错误.在未来的良好实践中,我该怎么做才能避免这个问题?

    public void loadFromFile()
    {
        OpenFileDialog oFile = new OpenFileDialog();
        oFile.Title = "Open text file";
        oFile.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
        oFile.FilterIndex = 1;
        oFile.InitialDirectory = Application.StartupPath;
        oFile.AddExtension = true;
        oFile.CheckFileExists = true;
        oFile.CheckPathExists = true;

        // Open and clean Duplicates
        String[] lines;
        List<string> temp = new List<string>();
        List<string> newlist = new List<string>();

        if(oFile.ShowDialog() == DialogResult.OK)
        {
            // Dummy file has 6 lines of text. Filename:DuplicatFile.txt
            // 3 duplicate lines and 3 not.
            lines = File.ReadAllLines(oFile.FileName, System.Text.Encoding.UTF8);

            // Copy array to temporary array
            for (int index=0; index < lines.Length; index++)
            {
                // System.ArgumentOutOfRangeException was unhandled
                // Index was out of range. Must be non-negative and less than the size of the collection.
                if (lines[index].Length >= 0)
                {
                    temp[index] = lines[index];
                }
            }
            // Check for duplicates. If duplicate ignore if non-duplicate add to list.
            foreach (string line in temp)
            {
                if (!newlist.Contains(line))
                {
                    newlist.Add(line);
                }
            }
            // Clear listbox and add new list to listbox.
            lstBox.Items.Clear();
            foreach (string strNewLine in newlist)
            {
                lstBox.Items.Add(strNewLine);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Mud*_*Mud 8

List<string> temp = new List<string>();
...
temp[index] = lines[index];
Run Code Online (Sandbox Code Playgroud)

temp从0开始.任何指数都超出范围.

您可以通过使用temp.Add,以使列表动态增长来解决此问题:

temp.Add(lines[index]);
Run Code Online (Sandbox Code Playgroud)