简体   繁体   English

C#公共静态字典

[英]C# public static dictionary

So I'm trying to make a publicly accessible dictionary for my entire program to access, I created that under my Form as such: 因此,我正在尝试为我的整个程序创建一个可公开访问的字典,我在我的表单下创建了这样的字典:

public static Dictionary<string, int> categories = new Dictionary<string, int>
    {
    {"services", 0},
    {"files", 0},
    {"shortcuts", 0},
    {"registry", 0},
    {"browsers", 0}
    };

Now, inside of a private method, I have this code: 现在,在私有方法内部,我有这样的代码:

                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;

This is basically breaking up a log file in sections to count the lines in between those sections declared in the category dictionary. 这基本上是在分段中分解日志文件,以计算类别字典中声明的那些部分之间的行。 Now my problem is the line of code 现在我的问题是代码行

categories[reference.Key] = stop - start;

keeps throwing an Invalid Operation Exception Error. 不断抛出无效的操作异常错误。 What am I doing wrong here? 我在这做错了什么?

You cannot change collection (and Dictionary is collection too) inside foreach loop for it. 你不能在foreach循环中更改集合(以及Dictionary也是集合)。 You can do quick workaround by creating duplicate collection as follows: 您可以通过创建重复集合来执行快速解决方法,如下所示:

foreach (KeyValuePair<string, int> reference in categories.ToList())

You try to change csope-closed varible (categories) in foreach loop. 您尝试在foreach循环中更改csope-closed变量(类别)。 It is unavalible operation. 这是不可行的操作。

It is simply to understand, as if you are allowed to change varible can be stored in out-of-memory stack. 它只是理解,好像你被允许更改varible可以存储在内存不足的堆栈中。

Use anouther varible, as example, to make this operation. 例如,使用anouther varible进行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM