所以我正在制作一个抢劫系统,计时器在第一次启动时完美运行,但在第二次尝试时它会缩短时间2次...意味着计时器的顺序下降是10,9,8,7 .....但是在第二次尝试序列是10,8,6,4 ......第3次尝试它的10,7,4,1 ..... Etc意思在每次启动时定时器序列增加减少时间?怎么可能?
public void robberyCountdown(User player)
{
time = 10;
cd.Elapsed += (source, e) => OnTimer(player);
cd.Start();
}
public void OnTimer(User player)
{
cd.Stop();
cd.Elapsed -= (source, e) => OnTimer(player);
}
答案 0 :(得分:0)
将您创建的代理保存到私有字段中,以便稍后访问:
private ElapsedEventHandler _onTimer;
public void robberyCountdown(User player)
{
time = 10;
_onTimer = (source, e) => OnTimer(player)
cd.Elapsed += _onTimer;
cd.Start();
}
public void OnTimer(User player)
{
cd.Stop();
cd.Elapsed -= _onTimer;
}
当然,这种方法假设player
对于两者都是相同的。更好的方法可能是让你的代表保持不变,并使用私有字段来跟踪哪些玩家正在计时。
private HashSet<Player> _timedPlayers = new HashSet<Player>();
public MyClass() // or whatever your constructor is called
{
cd.Elapsed += OnTimer;
}
public void OnTimer(Object source, ElapsedEventArgs e)
{
foreach(var player in _timedPlayers)
{
// ...
}
}
public void robberyCountdown(User player)
{
time = 10;
_timedPlayers.Add(player);
cd.Start();
}
public void OnTimer(User player)
{
cd.Stop();
_timedPlayers.Remove(player);
}