如何在 C# 接口中调用事件?
所以我有一个设计问题。 我有一个具有委托和事件的鼠标类。 即MouseButtonPressed、MouseMoved。 以及由状态引擎调用的此类内容。
我想要发生的是创建一个像 IClickable 或 IDraggable 之类的接口,并在这些接口中包含事件,这些事件在调用鼠标事件时被调用。
public interface IClickable
public event MouseDevice.ButtonClickedHandler<MouseButtons, MouseState> Clicked;
然后在 MouseDevice 类中它有
public delegate void ButtonClickedHandler<O, S>(object sender, InputDeviceEventArgs<O, S> e);
,
public event ButtonClickedHandler<MouseButtons, MouseState> ButtonClicked;
所以基本上我希望在调用 buttonClicked 时调用 Clicked 。
有没有办法做到这一点?
So i have a design problem. I have a mouse class that has delegates and events. ie MouseButtonPressed, MouseMoved. and such that are getting called by a state engine.
What i want to have happen is to create an interface like IClickable or IDraggable or somthing and have events inside those interfaces that get called when the mouse event gets called.
public interface IClickable
public event MouseDevice.ButtonClickedHandler<MouseButtons, MouseState> Clicked;
then in the MouseDevice class it has
public delegate void ButtonClickedHandler<O, S>(object sender, InputDeviceEventArgs<O, S> e);
and
public event ButtonClickedHandler<MouseButtons, MouseState> ButtonClicked;
So basically I want to have Clicked be called when buttonClicked gets called.
Is there a way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的意思是这样的吗?
You mean something like this?
当您在接口内声明事件时,它实际上并不会创建可以调用的事件 - 然后您必须在实现该接口的任何类中实现该事件。
由于接口不能包含任何代码,因此您必须在所有实现类中单独添加 OnMouseClicked 方法(或其他方法)才能调用类中的事件。 您还可以使 OnMouseClicked 成为界面本身的扩展方法,但这稍微颠覆了扩展方法的用途......
When you declare an event inside an interface, it doesn't actually create the event that can be called - you have to then implement that event within any classes that implement the interface.
As interfaces can't contain any code, you will have to add the OnMouseClicked method (or whatever) in all your implementing classes separately to call the event in the class. You could also make OnMouseClicked an extension method on the interface itself, but that is slightly subverting what extension methods are meant for...