>我正在尝试查找触发计时器的索引。
我在程序中创建了一个类条目列表.cs
static public List<Entry> Table = new List<Entry>();
这是名为"Entry"的类,其构造函数位于Entry中.cs
public class Entry
{
public int pktID;
public Timer pktTimer= new Timer();
}
public Entry()
{
}
public Entry(int _pktID, Boolean idleTimeOutStart)
{
this.pktID = _pktID;
if (idleTimeOutStart == true)
{
pktTimer.Elapsed += (sender, e) => CallDeleteEntry(sender, e, Program.Table.IndexOf());
pktTimer.Interval = 10000; // 10000 ms is 10 seconds
pktTimer.Start();
}
}
static void CallDeleteEntry(object sender, System.Timers.ElapsedEventArgs e, int pktIndex)
{
Program.Table.RemoveAt(pktIndex); //Removes Entry at this Index
Program.Table[pktIndex].idleTimeOutTimer.Stop(); //Stops idleTimeOutTimer of This Entry
}
列表中的项是随机创建的。现在列表(列表索引(中的每个计时器都将启动,然后在 10000 毫秒后,应调用 CallDeleteEntry。
我需要做的是在计时器经过 10000 毫秒时将计时器的索引传递给 CallDeleteEntry,以便它可以删除列表中的该项行。
我认为这里必须修改一些东西才能使其工作。
idleTimeOutTimer.Elapsed += (sender, e) => CallDeleteEntry(sender, e, Program.Table.IndexOf());
列表将如下所示
列表索引 |参赛项目
0 | PKT |pktTimer
1 | PKT |pktTimer
2 | PKT |pktTimer
3 | PKT |pktTimer
4 | PKT |pktTimer
你非常接近的 IndexOf 需要你尝试获取索引的项目。 在本例中,您尝试获取其索引的 Entry 类。我相信在你的情况下,这将是关键词这个,所以 IndexOf(这个(。
https://msdn.microsoft.com/en-us/library/8bd0tetb(v=vs.110(.aspx
@Jason Mastnick
导致我在评论中提到的上述错误的是
Program.Table.RemoveAt(pktIndex); //Removes Entry at this Index
Program.Table[pktIndex].idleTimeOutTimer.Stop(); //Stops idleTimeOutTimer of This Entry
我应该先停止计时器,然后删除数据包
Program.Table[pktIndex].idleTimeOutTimer.Stop(); //Stops idleTimeOutTimer of This Entry
Program.Table.RemoveAt(pktIndex); //Removes Entry at this Index
顺便说一下,您的解决方案有效。我应该这样写。
pktTimer.Elapsed += (sender, e) => CallDeleteEntry(sender, e, Program.Table.IndexOf(this));
但是,会出现一个问题。我尝试按顺序在列表中添加条目。传递的第一个 pktIndex 是 "1" 而不是 "0"。由于第一项是在索引 0 处添加的。它应该是在此顺序方案中首先删除的那个。一切正常,预计索引 0 处的第一项不会被删除。有什么想法吗?