列出超出范围

时间:2014-05-27 07:01:53

标签: c# winforms timer

我正在构建SJF算法。我有一本字典,我把它划分为2个列表。名称的一个列表和值的另一个列表。当然,在我对它进行排序之后,字典就会分开。我也有一个计时器。

当我运行代码时,它在列表中崩溃,它告诉我

  

指数超出范围。必须是非负数且小于集合的大小。

我不知道那是怎么回事,因为我的循环正好是字典的大小和列表的大小。

请告诉我如何解决这个问题?

   //Initializing the Dictionary  and the lists. 
    Dictionary<int, int> waytosave = new Dictionary<int, int>();

    List<int> saveName = new List<int>();
    List<int> saveValue = new List<int>();



   //Botton to run the algorithm 

        private void btnSFJ_Click(object sender, EventArgs e)
    {

        //the values inside the dictionary 
        waytosave.Add(0,100);
        waytosave.Add(1,10);
        waytosave.Add(2,30);
        waytosave.Add(3,500);
        waytosave.Add(4,5);
        waytosave.Add(5,13);
        waytosave.Add(6,200);
        waytosave.Add(7,89);
        waytosave.Add(8,248);
        waytosave.Add(9,136);
        waytosave.Add(10,458);
        waytosave.Add(11,743);

将它划分为列表似乎是我同时获取值和名称的最佳方式。

        //Sort the dictionary by Value
        foreach(KeyValuePair<int, Int32> saveSFJ in waytosave.OrderBy(key => key.Value))
        {
            saveName.Add(saveSFJ.Key);
            saveValue.Add(saveSFJ.Value);
            txtOutput.Text += "\r\r\n" + "The name is:  " + saveSFJ.Key + "  the value is:  "+ saveSFJ.Value;

        }
        int numsaving = 12;
        int timesaving=0;


        for (int x = 0; x < numsaving; x++)
        {
            var timer = new System.Windows.Forms.Timer();
            int track = 1;
            timer.Tick += (timerObject, timerArgs) =>
            {
                timer.Interval = track * saveValue[x]*1000; //I am getting crashed at this point When ever my loop finished. 
                this.txtOutput.Text += "\r\r\n" + " the value is:   "
                                                + saveValue[x]
                                                + "The name is:     "
                                                + saveName[x];

                timesaving = timesaving + saveValue[x];
                ++track;
                if (track > numsaving)
                {
                    timer.Stop();
                    timer.Dispose();

                }
            };
            timer.Start();

        }
        this.txtOutput.Text += "\r\r\n" + "  Ends x " + timesaving.ToString();

    }
}

当循环完成运行并且它只运行一次

时,我崩溃了

1 个答案:

答案 0 :(得分:1)

您的循环变量x获得captured in a closure

timer.Tick后面的代理运行时,x将不是您创建函数时的值,而是{{1>}的当前值(因为它被捕获)。目前,x将等于x(由于numsaving循环中的x++。)

要解决此问题,您可以将for的值复制到另一个局部变量中,例如:

x

您还可以使用简单的int y = x; timer.Tick += (timerObject, timerArgs) => { timer.Interval = track * saveValue[y]*1000; //I am getting crashed at this point When ever my loop finished. this.txtOutput.Text += "\r\r\n" + " the value is: " + saveValue[y] + "The name is: " + saveName[y]; timesaving = timesaving + saveValue[y]; ++track; if (track > numsaving) { ... 循环;如果您使用的是Visual Studio 2012,则不必创建迭代变量的本地副本:

foreach