C#公共静态字典

use*_*018 3 .net c# dictionary

因此,我正在尝试为我的整个程序创建一个可公开访问的字典,我在我的表单下创建了这样的字典:

public static Dictionary<string, int> categories = new Dictionary<string, int>
    {
    {"services", 0},
    {"files", 0},
    {"shortcuts", 0},
    {"registry", 0},
    {"browsers", 0}
    };
Run Code Online (Sandbox Code Playgroud)

现在,在私有方法内部,我有这样的代码:

                foreach (KeyValuePair<string, int> reference in categories)
            {
                for (int i = 0; i < scanLines.Count; i++)
                {
                    if (scanLines[i].Contains(reference.Key))
                    {
                        start = i + 1;
                        break;
                    }
                }
                for (int i = start; i < scanLines.Count; i++)
                {
                    if (scanLines[i].Contains("*"))
                    {
                        stop = i - 1;
                        break;
                    }
                }
                // Write the result for the category by subtracting the difference between
                // the start and stop variables
                categories[reference.Key] = stop - start;
Run Code Online (Sandbox Code Playgroud)

这基本上是在分段中分解日志文件,以计算类别字典中声明的那些部分之间的行.现在我的问题是代码行

categories[reference.Key] = stop - start;
Run Code Online (Sandbox Code Playgroud)

不断抛出无效的操作异常错误.我在这做错了什么?

Ulu*_*rov 5

您无法Dictionaryforeach循环内更改集合(也是集合).您可以通过创建重复集合来执行快速解决方法,如下所示:

foreach (KeyValuePair<string, int> reference in categories.ToList())
Run Code Online (Sandbox Code Playgroud)