c#用于1个循环后退出的循环
本文关键字:循环 退出 1个 用于 | 更新日期: 2023-09-27 18:28:54
在我的项目中,我尝试对值进行循环并调用它们上的函数。当调试Count时,告诉我有2个值。我的函数在DispatcherTimer 中运行
我在构造函数中的计时器:
DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(runSync);
dispatcherTimer.Interval = new TimeSpan(0, 0, syncTime);
dispatcherTimer.Start();
我的功能
private void runSync(object sender, EventArgs e)
{
//I can see the value of count is 2 when using break points
List<string> vals = repo.getRemovedAnswers();
for (int i = 0; i < vals.Count(); i ++ )
{
//i do something with the element in my database
// send back a confirmation that the delete is finished
repo.setAnswerDeleted(vals.ElementAt(i));
Console.WriteLine(i + " removed");
//
}
Console.WriteLine("syncing");
}
函数setAnswerDeleted在我的repo类中,它是一个void方法,所以不会返回break或任何东西。
public List<String> getRemovedAnswers()
{
return _answersRemoved;
}
public void setAnswerDeleted(string uniqueIdAnswer)
{
_answersRemoved.RemoveAll( item => item == uniqueIdAnswer);
}
在日志中,我可以看到循环在每个dispatchtimer循环中运行,onyl调用方法1次,为什么当count==2时for循环没有运行2次?
尝试以这种方式更改代码:
private void runSync(object sender, EventArgs e)
{
//I can see the value of count is 2 when using break points
List<string> vals = repo.getRemovedAnswers();
for (int i = vals.Count() - 1; i >= 0; i--)
{
repo.setAnswerDeleted(vals.ElementAt(i));
Console.WriteLine(i + " removed");
//
}
Console.WriteLine("syncing");
}
您的for迭代一次,因为您从列表中删除了元素,并将索引增加了一,但删除后的元素的前一个长度为-1,因此下一次检查vals。Count()返回1,您的索引为1。这样,您的索引从1开始,第二步为0。
问题是,在对列表进行迭代时,您正在修改该列表,因此它将删除元素,并且Count()结果将在每个循环中递减。最佳做法是返回列表的副本,这样您就不会在执行过程中对其进行修改。
List<string> getRemovedAnswers()
{
.. logic
List<string> previousReturn = ...
return new List<string>(previousReturn);// Creates new list
}
另一个好的做法是使用foreach
循环,而不是按索引进行。
foreach(var element in vals)
{
repo.setAnswerDeleted(element);
}
如果你这样做了,它会抛出一个异常,说集合在迭代时被修改了。这会立即提醒你这个问题。