2014-01-17 30 views
-2
foreach(string file in strAllFiles) 
{ 
    foreach(char c in file) 
    { 
     if (c > 127) 
     { 
      using (SqlConnection con = new SqlConnection(CS)) 
      { 
       con.Open(); 
       SqlCommand sqlcom = new SqlCommand("sp_ReplaceNonAsciiCharset", con); 
       sqlcom.CommandType = CommandType.StoredProcedure; 
       SqlParameter sqlparam = new SqlParameter(); 
       sqlparam.ParameterName = "@non_ascii_char"; 
       sqlparam.Direction = ParameterDirection.Input; 
       sqlparam.SqlDbType = SqlDbType.NChar; 
       sqlparam.Size = 2; 
       sqlparam.Value = c; 
       sqlcom.Parameters.Add(sqlparam); 
       object o = sqlcom.ExecuteScalar(); 
       int i = file.IndexOf(c); 
       file1 = file.Remove(i, 1); 
       file2 = file1.Insert(i, o.ToString()); 
       file = file2; 
      } 
     } 
    } 
} 

在最後一行file=file2,我得到的錯誤:的foreach迭代變量錯誤是給

cannot assign to file because it is a foreach iteration variable

+0

請明確說明你打算做什麼!如果你不指定你想要做什麼,我們不能幫助解決它! –

+1

檢查http://stackoverflow.com/questions/3551696/why-cant-i-modify-the-loop-variable-in-a-foreach – link64

+3

該錯誤是相當自我解釋..你試圖分配一個值到「foreach」迭代的一部分的變量。 –

回答

2

它,因爲你正在改變這是不允許的循環變量。一種選擇是將file1添加到單獨的列表或,如果使用「for」循環而不是foreach,則可以修改它。

1

本聲明

file = file2; 

需要改變。因爲您無法將值分配給您在foreach中循環的變量。也許,將它分配給一些新的變量。迭代變量是隻讀的,不能更改。來自c#語言規範的Section 8.4.4

The iteration variable corresponds to a read-only local variable with a scope that extends over the embedded statement. During execution of a foreach statement, the iteration variable represents the collection element for which an iteration is currently being performed. A compile-time error occurs if the embedded statement attempts to modify the iteration variable (by assignment or the ++ and -- operators) or pass the iteration variable as a ref or out parameter.

1
  1. 如果你想修改strAllFiles收集你應該使用 用於代替的foreach:
  2. 不要試圖修改文件中 的foreach(炭下,在文件中)

喜歡的東西

for(int i=0; i < strAllFiles.Count; i++) 
{  
    var file = strAllFiles[i];  
    var newFileValue = file;  
    foreach(char c in file) 
    { 
     if (c > 127) 
     { 
     using (SqlConnection con = new SqlConnection(CS)) 
     { 

      ... 
      // modify newFileValue 
      newFileValue = file2; 

     } 
     } 
    } 
    // Modify collection 
    strAllFiles[i] = newFileValue; 
} 
+0

這裏strAllfiles是一個字符串數組它包含6個文件。我如何在這裏使用我 user3203633

+0

它從您放入的代碼中看不到,它是strAllFiles。只需將計數替換爲長度。 – AlexS