-4

我使用 List 来存储值,如果数据有限,它可以正常工作,如果数据超过 15o 的计数,那么我收到以下错误 Index was outside the bounds of the array ...Plz建议一个想法克服这个问题。

List<string> code = new List<string>();
private void btn_browse_Click(object sender, EventArgs e)
{
    DialogResult fileopen = openFileDialog1.ShowDialog();
    string filename = openFileDialog1.FileName;           
    txt_filename.Text = filename;
    try
    {
        StreamReader readtxtfile = new StreamReader(filename);
        String line = null;

        string str = null;
        char[] separate = { ',' };
        string[] words;
        while ((str = readtxtfile.ReadLine()) != null)
        {
            words = str.Split(separate);                        
            code.Add(Convert.ToString(words[0]) + '-' + Convert.ToString(words[2]).Trim());  
        }                    
    }
4

1 回答 1

1

此错误不是因为您的列表,而是来自您的数组“单词”。首先像这样检查数组的长度

 words = str.Split(separate);  
 if(words.Length>2) 
 {                     
   code.Add(Convert.ToString(words[0]) + '-' + Convert.ToString(words[2]).Trim());  
 }

确保只要数组的长度小于 2,它就不会添加到您的列表中。

希望这可以帮助...

于 2012-10-05T07:29:41.220 回答