我正在实现一个 Buthon_Click 方法,顾名思义,它与事件 onclick 按钮一起使用。现在为了让这个方法执行我想要的操作,我需要清除/取消绑定(bind)/取消订阅附加到 的委托(delegate)SystemEvents.SessionSwitch
事件。问题是我想这样做而不关心之前连接了哪种方法。
例如:
SystemEvents.SessionSwitch += new SessionSwitchEventHandler(Methodx);
所以我现在正在做的是创建一个 foreach 并检查所有可能性 - 总共 4 个:
int [] array={1,2,3,4};
foreach (int n in array)
{
SystemEvents.SessionSwitch -= new SessionSwitchEventHandler(SystemEvents_SessionSwitch1);
SystemEvents.SessionSwitch -= new SessionSwitchEventHandler(SystemEvents_SessionSwitch2);
SystemEvents.SessionSwitch -= new SessionSwitchEventHandler(SystemEvents_SessionSwitch3);
SystemEvents.SessionSwitch -= new SessionSwitchEventHandler(SystemEvents_SessionSwitch4);
}
我发现这种代码的和平有点麻烦和笨拙,我想知道是否有更“优雅”的方式来做这件事,比如 SystemEvents.SessionSwitch == null
或类似的会消灭所有连接的方法吗?
提前致谢
最佳答案
这取决于谁“拥有”SystemEvents.SessionSwitch
。通常,您无法从外部设置 事件处理程序列表 - 您只能添加或删除它们。这就是封装级别。
您应该区分事件 和任何可能碰巧是事件后备存储的变量。事件只支持订阅和移除。看我的article on events and delegates获取更多信息。
请注意,您现有的代码可能已经更整洁了:
foreach (int n in array)
{
SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch1;
SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch2;
SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch3;
SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch4;
}
...虽然您在这里没有使用 n
,但您并不清楚为什么要循环。
关于c# - 清除事件的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4023948/