[英]C# Event Handlers getting more and more
我现在正在写一个简单的国际象棋游戏。
在我的游戏中有“ Chessfields”和“ Options”。 Chessfield是棋盘上的每个字段,选项是该字段上人物的每个移动可能性。
因此,当我单击国际象棋场时,对于每个选项字段,我都会绑定一个新的事件处理程序。
像这样:
private void Chessfield_Click(object sender, MouseButtonEventArgs e)
{
// ... some other stuff
PlaceOptions();
// ... some other stuff
}
函数PlaceOptions()执行此操作的位置:
private void PlaceOptions(List<(int, int)> Options, int SourceX, int SourceY)
{
foreach ((int, int) option in Options)
{
// ... some other stuff
chessfield.MouseDown -= Chessfield_Click;
// should remove all existing handlers for that field
foreach (MouseButtonEventHandler optionClickHandler in _recentOptionClickHandlers)
{
chessfield.MouseDown -= optionClickHandler;
}
chessfield.MouseDown += (sender, e) => Option_Click(sender, e, chessfield, SourceX, SourceY);
_recentOptionClickHandlers.Add((sender, e) => Option_Click(sender, e, chessfield, SourceX, SourceY));
// ... some other stuff
}
}
_recentOptionClickHandlers
是一个全局变量,用于存储我添加到任何选项字段的每个处理程序:
private List<MouseButtonEventHandler> _recentOptionClickHandlers = new List<MouseButtonEventHandler>();
现在:每次单击国际象棋场时, Chessfield_Click()
处理函数仅被调用一次。
但这带来了问题:当我然后单击一个选项字段(因此可能移动图形)时,所有最近单击的普通象棋字段都移至该字段,因为所有先前的处理程序仍处于活动状态,但是我已经删除了它们通过致电:
foreach (MouseButtonEventHandler optionClickHandler in _recentOptionClickHandlers)
{
chessfield.MouseDown -= optionClickHandler;
}
而且我点击任何字段越多,调用的事件处理程序就越多(第一次:1个处理程序;第二次:2个处理程序;第三次:4个处理程序; ...)
自从两天以来,这个问题确实使我发疯。
提前致谢
现在无法测试,也无法发表评论,所以我在这里回复。
我认为添加到_recentOptionClickHandlers
的处理程序与您为MouseDown
事件注册的处理程序不同,因为要在将其添加到列表之前创建一个新的delegate
。
您应该尝试这样的事情:
EventHandler evt = (sender, e) => Option_Click(sender, e, chessfield, SourceX, SourceY);
chessfield.MouseDown += evt;
_recentOptionClickHandlers.Add(evt);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.