【问题标题】:Collection modified error, when iterating using foreach loop [duplicate]使用 foreach 循环进行迭代时,集合修改错误 [重复]
【发布时间】:2015-03-03 03:27:41
【问题描述】:

我的应用程序中有以下功能:

// Method To Save Logs Buffer In Memory To DB
public void SaveLogsToDB()
{
    // Proceed If There Is Any Logs In Buffer
    if (LogsViewer.DBLogEntries.Count > 0)
    {
        // Init
        string massInertStr = "INSERT INTO IC_Logs ([Date], [Time], [Type], [Entry], [Synced], [CreatedOn]) VALUES ";

        // Build Mass Insert String
        List<DBLog> currentLogEntries = LogsViewer.DBLogEntries;
        foreach (DBLog myDBLog in currentLogEntries)
        {
            // Generate Insert Statement
            massInertStr += String.Format("('{0}', '{1}', '{2}', '{3}', 0, GETDATE()),",
                myDBLog.Date,
                myDBLog.Time,
                myDBLog.Type,
                myDBLog.Entry.Replace("'", "''"));
        }
        massInertStr = massInertStr.Remove(massInertStr.Length - 1);

        // Expect Errors
        try
        {
            // Execute Mass Insert
            MyDb.ExecuteNonQuery(massInertStr);

            // Clear Logs Buffer
            LogsViewer.DBLogEntries.RemoveAll(item => currentLogEntries.Contains(item));
        }
        catch { }
    }
}

当我的应用程序运行时,我时不时会收到以下异常:

集合已修改;枚举操作可能无法执行。

错误出现在这一行:foreach (DBLog myDBLog in currentLogEntries) { ... }

currentLogEntries 不是集合的副本而不是参考吗?我不确定为什么会发生此错误或如何防止它。

【问题讨论】:

  • 会有这样的帮助吗(在我运行 foreach 循环之前):DBLog[] currentLogEntries = new DBLog[LogsViewer.DBLogEntries.Count]; LogsViewer.DBLogEntries.CopyTo(currentLogEntries); ?
  • Isn't currentLogEntries a copy of the collection rather than a reference? 不,这是一个参考。
  • currentLogEntries 不是副本。它是同一参考文献的副本。您需要获取集合的副本或使用并发集合。建议的副本应该会有所帮助。
  • 顺便说一句,在将可能大量的字符串连接在一起时,请考虑使用StringBuilder
  • 除了@StuartLC所说的,永远不要连接字符串来形成sql查询。它容易受到SQL injection attacks 的攻击。

标签: c# collections


【解决方案1】:

你最好这样做来深度克隆你的列表:

List<DBLog> currentLogEntries = new List<DBLog>(LogsViewer.DBLogEntries);

【讨论】:

  • 谢谢,我现在就试试。
猜你喜欢
  • 1970-01-01
  • 2010-11-10
  • 2021-07-14
  • 1970-01-01
  • 1970-01-01
  • 2018-11-18
  • 2013-10-09
  • 1970-01-01
  • 2014-09-19
相关资源
最近更新 更多