【发布时间】:2016-02-22 23:06:57
【问题描述】:
我之前发过一个问题,这里: C# Array of List Index out of bounds 它的代码大致相同。我的代码工作正常,但是当它完成一个文件时,它没有中断到下一个文件名(在 foreach 循环中),它保持不变 - 这样匹配总是重复,他只是在不同的列表位置添加相同的东西。我试过改变 fs.Close() 的位置,添加一个 break 语句,但这些都不起作用。
在这种情况下我做错了什么?在我的逻辑视图中,它应该在完成特定文件后转到外循环。
我根据最低需求编辑了代码 - 无论如何,这里有一个完整代码的链接: http://pastebin.com/xcKczQLC
整个代码的这个链接包含我打开文件的部分。
谢谢。
foreach (string fileName in fullFileName) //Start processing each file
{
// Lots of code here - reading a mixed file - no need to show
bool b = filecontents.Contains("CIP3EndOfFile");
if(b)
{
//Code manipulating contents in filecontents (a string)
var matches = Regex.Matches(query, pattern);
//When the foreach (Match m in matches) loop ends he always returns to the line above
finalcontent[listpos] = new List<xmldata>();//Initializing a list for each filename
foreach (Match m in matches)
{
//Lots of code doing some operations with the found match
if (i < colors_str.Length)
{
finalcontent[listpos].Add(new xmldata//The exception is thrown right here
{
colorname = colors_str[i],
colorvalues = values,
});//Closing list add declaration
}//Closing if
i++;
}//Closing foreach loop
if (i >= colors_str.Length)
{
listpos++;
i = 0;
}
fs.Close();//closing current file
//In this moment i expected that it would go for the foreach (string fileName in fullFileName) loop
//Instead he returns to this inner foreach loop
}//Closing boolean if
}//End file reading - closing for
}//Finished processing each filename (string filename in filename)
【问题讨论】:
-
你在哪里打开文件?
-
它是代码的另一部分——为了符合社区标准,我将代码减少到分析所需的最低限度。但我发布了整个代码的链接。
-
@KeithHall 不,不是重复的
-
我也看过这篇文章。但是除了使用 goto 或 break 语句之外,还有什么解决方案吗?我相信可能涉及减少循环(仅使用一个然后使用常规 for 而不是另一个 foreach - 也许)?
标签: c# foreach nested-loops