【发布时间】:2012-06-05 01:21:56
【问题描述】:
我正在尝试找到创建系统的最佳方法,在该系统中可以将事件源添加到管理器类中,然后该管理器类会将其事件重新分配给侦听器。具体来说,我有许多不同的输入源(键盘输入源、鼠标输入源、虚拟键盘输入源等),我希望开发人员能够监听键盘输入源和输入端的 KeyDown 事件管理器本身(从任何活动输入源捕获此事件)。
很容易暴力破解一个解决方案,我最终创建了许多“调度”函数,当它们通过时简单地重新调度事件,但我最终有几十个单行函数,我必须创建新函数每当向输入源界面添加新事件时。
我考虑过使用 lambda,但如果从管理器中删除输入源,我需要一种方法来解除事件挂钩。我可以将 lambda 保存在字典中,由输入源键入,但是许多事件具有不同的 arg 类,并且为此创建多个字典开始变得丑陋。
我想知道我是否遗漏了一些简单的方法来保持清洁并保持我需要写下的额外代码量。
作为参考,这是我正在使用的对象的示例:
public interface IInputSource {}
public interface IKeyboardInputSource : IInputSource
{
event EventHandler<KeyboardEventArgs> KeyDown;
event EventHandler<KeyboardEventArgs> KeyUp;
}
public interface IMouseInputSource : IInputSource
{
event EventHandler<MouseEventArgs> MouseDown;
event EventHandler<MouseEventArgs> MouseUp;
}
public class InputManager : IKeyboardInputSource, IMouseInputSource
{
private List<IInputSource> InputSources;
//Event declarations from IKeyboardInputSource and IMouseInputSource
public void AddSource(IInputSource source)
{
InputSources.Add(source);
if (source is IKeyboardInputSource)
{
var keyboardSource = source as IKeyboardInputSource;
keyboardSource.KeyDown += SendKeyDown;
// Listen for other keyboard events...
}
if (source is IMouseInputSource)
{
// Listen for mouse events...
}
}
public void RemoveSource(IInputSource source)
{
if (source is IKeyboardInputSource)
{
var keyboardSource = source as IKeyboardInputSource;
keyboardSource.KeyDown -= SendKeyDown;
// Remove other keyboard events...
}
if (source is IMouseInputSource)
{
// Remove mouse events...
}
InputSources.Remove(source);
}
private void SendKeyDown(object sender, KeyboardEventArgs e)
{
if (KeyDown != null)
KeyDown(sender, e);
}
//Other "send" functions
}
【问题讨论】:
-
我应该早点提到这一点——但不幸的是,我正在从事的项目不允许我使用任何第三方库。
-
您可以检查 bbvcommon 库中使用的代码,因为它是开源的,然后您可以复制它并使其适应您的代码。这是源代码的直接链接github.com/bbvcommon/bbv.Common
-
好点。我去看看!
标签: c# events architecture lambda