C# foreach循环:循环变量can';赋值(?)后不能修改
我有以下代码:C# foreach循环:循环变量can';赋值(?)后不能修改,c#,regex,C#,Regex,我有以下代码: string STR = "AA ABC AA AA ABC aa aa aa AA" ; //declare string Regex rx = new Regex(@"AA"); // declare regular expression MatchCollection matches = rx.Matches(STR); // find matches in STR foreach (Match match in matches) { // perform
string STR = "AA ABC AA AA ABC aa aa aa AA" ; //declare string
Regex rx = new Regex(@"AA"); // declare regular expression
MatchCollection matches = rx.Matches(STR); // find matches in STR
foreach (Match match in matches)
{
// perform sub-string operations that changes the original string
STR = "AA AA ABC aa aa aa AA" // substring operation which arbitrary changes the string
matches = rx.Matches(STR); // perform matching operation again
// because original string is changed
// ERROR : 'matches' in for loop is not changed (?)
// Question: how can I change 'matches' in for loop, thus it will start
// to work in new modified string ?
}
有人能帮我解决上面的问题吗
编辑:
int j = 15
for (int i = 0 to j){
// change both i and j value arbitrarily
i = 100
j = 102
changes is reflected in original for loop
}
在第一种情况下,我希望改变反射。但是,“matches”中的更改不会反映在foreach循环中。这就是问题所在。如何解决此问题?您不应该修改当前迭代的对象:首先创建原始对象的副本,然后将更改应用于副本。您正在枚举
匹配项,因此,如果您更改匹配项,则在对其进行枚举时正在更改枚举。当然,这不起作用,您需要一个新变量来保存更改后的匹配项
只需为匹配项使用两个变量即可。1用于每个循环。。另一个根据您的意愿进行修改。或者使用带计数器的basic for循环。您不能修改当前使用的集合(foreach循环)。我仍然不确定您试图实现什么,但我认为递归可能会帮助您。这样,循环体将在所有原始匹配上运行,如果字符串更改,它也将在所有新匹配上运行。但是要注意无限递归
void ForEach(Regex rx, string str)
{
foreach (Match match in rx.Matches(str))
{
// code that might change str
// if(the str was changed)
ForEach(rx, str);
}
}
在for
循环中,您可以更改,但是您可以使用foreach
将代码修改为接受字符串(您的STR
)的函数,当您想要更改匹配项时,使用新字符串调用该函数。修改foreach集合是错误的,但您的代码对我来说运行正常。新值被分配给匹配项四次。@尼玛,用一些子字符串操作更改STR=“AA AA ABC AA AA AA”行,该操作会任意更改字符串。情况并非如此。matches变量的值已更改,而不是匹配本身。代码不会抛出异常,它只是与作者的行为不同expected@lisp:在foreach
-循环中枚举您试图更改的同一个变量不是一个好主意。“行为和作者预期的不同”可以解释为“不起作用”,对吗确实,最初的代码是“糟糕的”,但问题不是你所描述的。