【发布时间】:2021-08-05 18:30:42
【问题描述】:
我正在使用基于列表中项目数声明 INT 的 for 循环。我正在填充的列表是动态的,基于目录中的文件列表。逻辑应该是,如果计数等于或超过 1k 条记录,则一次加载 1k 条记录,否则,如果计数较少,则计算列表中的项目并将其设置为 for 循环的最大值。然而 for 循环只运行 499 次并且出现错误(图片)。 THIS ERROR IMAGE.
有人知道如何解决发生的错误吗?
下面是代码的核心,便于理解。
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
using System.Linq;
namespace ViewProductImages
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//new list
List<string> filenames = new List<string>();
private void txtDirectory_TextChanged(object sender, EventArgs e)
{
//clear list - added peace of mind
filenames.Clear();
//list is populated here via Directory.Getfiles
//Sorted here kinda
filenames.Sort();
}
//Declare INT for for loop
int maxImagesToShow;
private void button1_Click(object sender, EventArgs e)
{
//Setting value for INT - IF over 1k records, set to 1k, IF under - set to actual list item count
if (filenames.Count() >= 1000)
{
maxImagesToShow = 1000;
}
else
{
maxImagesToShow = filenames.Count();
}
try
{
//for loop - loops based on value in INT
for (int i = 0; i < maxImagesToShow; i++)
{
var filename = filenames[i];
//remove current item being processed from the list(filenames)
filenames.Remove(filename);
}
}
catch (Exception ex)
{
}
}
}
}
【问题讨论】:
-
提示:假设列表中有 5 个项目,那么您将从 0 到 4 进行迭代。然后你调用
Remove两次......列表中有多少项目?删除前两个元素后,元素 4 是什么? (为什么要在循环中完全删除项目?我建议使用 List.RemoveRange...) -
请记住在您的问题中包含错误消息及其堆栈跟踪作为文本。即使在屏幕截图中的对话框中,您也应该能够按 CTRL+C 并复制它。