我试图将一个整数值传递到ElapsedEventHandler中,以便我可以基于传入的整数执行逻辑。但是,当引发Event时,传入的值不是我将其初始化为的值。我可能没有完全理解代表的工作方式。
class Example
{
Dictionary<int, Timer> timer;
public Example()
{
timer = new Dictionary<int, timer>();
for(int i = 0; i < 12; ++i)
{
timer.Add(i, new Timer(5000));
timer[i].Elapsed += delegate { TimerTickCustom(i); };
}
}
public void Process() // called each cycle
{
for(int i = 0; i < 12; ++i)
{
timer[i].Start();
}
}
private void TimerTickCustom(int i)
{
// The value of i coming in does not match the dictionary key.
}
}
取决于本地值在哪里,i
代表将其视为其范围的“特定”值。正如i
在循环外部定义的那样,委托没有定义它自己的该变量的“副本”,因为所有委托都期望相同i
。
您需要做的是将其分配给与委托本身“处于同一级别”的变量。
不知道我是否在这里使用正确的语言来解释它。但这应该工作:
class Example
{
Dictionary<int, Timer> timer;
public Example()
{
timer = new Dictionary<int, Timer>();
for(int i = 0; i < 12; ++i)
{
int iInScopeOfDelegate = i;
timer.Add(i, new Timer(5000));
timer[i].Elapsed += delegate { TimerTickCustom(iLocalToDelegate ); };
}
}
public void Process() // called each cycle
{
for(int i = 0; i < 12; ++i)
{
timer[i].Start();
}
}
private void TimerTickCustom(int i)
{
// The value of i coming in does not match the dictionary key.
}
}
如果您知道要在搜索引擎中键入哪些单词,那么将会进行一些有趣的讨论(当然,只有在有人告诉您时您才能真正知道哪些单词)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句