列表超出范围
本文关键字:范围 列表 | 更新日期: 2023-09-27 18:05:23
我正在构建SJF算法。我有一个字典,我把它分成了两个列表。一个列表用于名称,另一个列表用于值。当然,我把字典整理好之后,它就分了。我也有一个计时器。
当我运行代码时它在列表中崩溃了它告诉我
索引超出范围。必须非负且小于集合的大小。
我不知道这是怎么来的,因为我的循环正好是字典的大小和列表的大小。
你能告诉我如何解决这个问题吗?
//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();
}
}
当循环结束运行时我崩溃了,它只运行一次
您的循环变量x
在闭包中被捕获。
当timer.Tick
背后的委托运行时,x
将不是您创建函数时的值,而是x
的当前值(因为它被捕获)。此时,x
将等于numsaving
(由于for
循环中的x++
)。
要解决这个问题,可以将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)
{
...
你也可以使用一个简单的foreach
循环;如果你使用的是Visual Studio 2012,你不需要创建迭代变量的本地副本:
foreach(var kvp in waytosave.OrderBy(key => key.Value))
{
var timer = new System.Windows.Forms.Timer();
int track = 1;
timer.Tick += (timerObject, timerArgs) =>
{
timer.Interval = track * kvp.Value *1000;
...