我最近修复了 在我的代码库中解决了一个非常烦人的问题。
我有一个ParentMenuItemBase
抽象类,我从中派生基本上包装CommandBarPopup
控件的类,并创建子CommandBarButton
个对象并将它们的Click
事件连接到执行ICommand
。
假设我有一个RefactorRenameCommand
连接了5个完全独立的CommandBarButton
个对象,在5个完全不相关的CommandBarPopup
控件下。
当我点击CommandBarButton
时,child_Click
处理程序将运行5次 - Ctrl
参数将具有相同的哈希码,用于所有5"点击&#34 ;
然后,如果我再次单击相同的按钮,处理程序将再次运行5次,Ctrl
参数将再次具有相同的哈希码,用于所有5"点击",...但是哈希码与第一次的哈希码不同 - 如果我再次点击,我会得到一个新参数的哈希码。
我通过在Ctrl
字段中存储该private static
参数的最后一个哈希码来获得所需的行为,并且只有Ctrl
的哈希码不同时才执行处理程序 - 在换句话说,我建立在一个我不完全理解的观察行为的基础上,并且感觉很脏,这使我无法言语。这是有问题的黑客,包括实际的代码内注释:
// note: HAAAAACK!!!
private static int _lastHashCode;
private void child_Click(CommandBarButton Ctrl, ref bool CancelDefault)
{
var item = _items.Select(kvp => kvp.Key).SingleOrDefault(menu => menu.Key == Ctrl.Tag) as ICommandMenuItem;
if (item == null || Ctrl.GetHashCode() == _lastHashCode)
{
return;
}
// without this hack, handler runs once for each menu item that's hooked up to the command.
// hash code is different on every frakkin' click. go figure. I've had it, this is the fix.
_lastHashCode = Ctrl.GetHashCode();
Debug.WriteLine("({0}) Executing click handler for menu item '{1}', hash code {2}", GetHashCode(), Ctrl.Caption, Ctrl.GetHashCode());
item.Command.Execute(null);
}
Debug.WriteLine
调用将输出如下内容:
(46595510) Executing click handler for menu item '&Rename', hash code 16706408 (16139946) Executing click handler for menu item '&Rename', hash code 16706408 (11041789) Executing click handler for menu item '&Rename', hash code 16706408 (32267243) Executing click handler for menu item '&Rename', hash code 16706408 (21969731) Executing click handler for menu item '&Rename', hash code 16706408
下一次点击会产生相同的输出,但Ctrl
参数的哈希码不同。
那么,这个Ctrl
参数究竟是什么?如果它是被点击的CommandBarButton
COM控件,那么为什么它的哈希码与我创建的CommandBarButton
对象的哈希码不匹配?为什么每次处理程序运行时它的哈希码都会改变?