的foreach迭代变量错误是给

问题描述:

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://*.com/questions/3551696/why-cant-i-modify-the-loop-variable-in-a-foreach – link64

+3

该错误是相当自我解释..你试图分配一个值到“foreach”迭代的一部分的变量。 –

它,因为你正在改变这是不允许的循环变量。一种选择是将file1添加到单独的列表或,如果使用“for”循环而不是foreach,则可以修改它。

本声明

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. 如果你想修改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