2014-02-21 144 views
-1

我有以下代碼:foreach循環:(?)循環變量不能分配後進行修改

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 
} 

在第一種情況下,我想這種變化的反映。但是,「匹配」中的更改不會反映在foreach循環中。這就是問題。如何解決它?

+0

在'for'循環,可以改變,但是你用'foreach' – Grundy

+0

修改代碼是一個'function'在一個字符串需要(你'STR'),當你想改變'匹配「,用新字符串調用該函數。 – NoLifeKing

+0

修改foreach集合是錯誤的,但你的代碼對我來說運行得很好。新值被分配爲匹配四次。 – nima

回答

0

您不應該修改您當前正在迭代的對象:首先創建原始對象的副本,然後將更改應用於副本。

1

你正在枚舉matches,所以如果你改變matches你正在改變枚舉,而你正在枚舉它。當然這不起作用,你需要一個新的變量來保存更改後的matches

+1

,但情況並非如此。匹配變量的值被改變了,不匹配它自己。代碼不會拋出異常,它的行爲與作者預期的不同 – lisp

+0

@lisp:在foreach循環中枚舉您想要更改的同一個變量並不是一個好主意。 「行爲與作者預期的不同」可以被解釋爲「不起作用」,對吧? ;) – waka

+0

這是真的,原來的代碼是「壞」,但問題不是你所描述的。 – lisp

0

只需使用兩個變量Matches。 1用於每個循環..其他修改如你所願。或者使用基本for循環與計數器。你不能修改一個積極使用的集合(foreach循環)。

0

我還不確定你想達到什麼,但我認爲遞歸可能會對你有幫助。這樣,您的循環體將運行在所有原始匹配上,並且如果字符串更改,它也會在所有新匹配上運行。雖然知道無限遞歸。

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); 
    } 
}