简体   繁体   English

C#使用接口订阅事件

[英]C# Subscribing to Events Using Interfaces

I have recently started working with C# events and I am really liking the ease of use they offer (I come from a java background where we have to do all this event stuff manually). 我最近开始使用C#事件,并且我真的很喜欢它们提供的易用性(我来自Java背景,我们必须手动完成所有这些事件工作)。

However, there is one thing from my java background that I am missing: the inheritance side. 但是,从我的java背景中我缺少一件事:继承方面。

In java, if you want to subscribe to an event, you would inherit an interface such as IKeyListener. 在Java中,如果要预订事件,则可以继承IKeyListener之类的接口。 The interface would contain all of the method event signatures which you would then implement in the subscribing class. 接口将包含所有方法事件签名,然后您将在订阅类中实现该方法签名。 Whenever a key would be pressed, these implemented methods would be fired. 每当按键被按下时,这些已实现的方法就会被触发。 Much the same as C#. 与C#大致相同。 However, unlike in java, I am unable to identify which classes subscribe to certain events because they don't actually inherit anything. 但是,与Java不同,我无法确定哪些类订阅了某些事件,因为它们实际上没有继承任何东西。

So if I wanted a list of objects which have key press event support I could do 因此,如果我想要一个具有按键事件支持的对象列表,我可以

List<IKeyListener> keyListeners = new ArrayList<IKeyListener>();

However, I don't see any good way to do this in C#. 但是,我在C#中看不到任何好的方法。 How would I be able to create list similar to the one above? 我将如何创建类似于上面的列表? Preferably without much "hackiness". 最好没有太多的“ hackackiness”。

Thank you. 谢谢。

In C# you can define the event in an interface like this: 在C#中,您可以在这样的接口中定义事件:

public interface IDrawingObject  
{  
    event EventHandler ShapeChanged;  
} 

Then you can do what you want and store them like this: 然后,您可以执行所需的操作并像这样存储它们:

var shapes = new List<IDrawingObject>();

A class can then implement the interface like this: 然后,一个类可以实现如下接口:

public class Shape : IDrawingObject  
{  
    public event EventHandler ShapeChanged;  
    void ChangeShape()  
    {  
        // Do something here before the event…  

        OnShapeChanged(new MyEventArgs(/*arguments*/));  

        // or do something here after the event.   
    }  
    protected virtual void OnShapeChanged(MyEventArgs e)  
    {  
        if(ShapeChanged != null)  
        {  
           ShapeChanged(this, e);  
        }  
    }  
} 

So in other words the event becomes part of the interface and if a class implements that interface, the class must provide an implementation for the event as well. 因此,换句话说,事件成为接口的一部分,如果类实现该接口,则该类也必须提供事件的实现。 That way you are safe to assume the implementing class has the event. 这样,您可以安全地假设实现类具有事件。

Finally every event will need to share some info about the event. 最后,每个事件都需要共享一些有关事件的信息。 That class can inherit the EventArgs class like below: 该类可以继承EventArgs类,如下所示:

public class MyEventArgs : EventArgs   
{  
    // class members  
}  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM