在接口中使用事件

The*_*kai 5 c# events delegates interface

我正在实现一个使用复合设计模式的菜单系统.我有以下MenuElement接口:

public interface MenuElement
{
    void AddMenuElement( MenuElement menuToAdd );
    void RemoveMenuElement( MenuElement menuToRemove );
    MenuElement GetMenuElement( int index );
    void Activate();
}
Run Code Online (Sandbox Code Playgroud)

我想在这个界面中包含一个"OnActivate"事件,以便实现此接口的MenuItems在激活时可以触发函数.我尝试像这样实现它:

public interface MenuElement
{
    public delegate void MenuEvent();
    event MenuEvent onActivate;

    void AddMenuElement( MenuElement menuToAdd );
    void RemoveMenuElement( MenuElement menuToRemove );
    MenuElement GetMenuElement( int index );
    void Activate();
}
Run Code Online (Sandbox Code Playgroud)

但是,编译器不允许我在接口内声明委托.我知道一个名为EventHandler的C#事件类型,但与我想要的MenuEvent不同,它需要object和EventArgs参数.我也考虑过移动我的事件并委托给MenuItem,但我仍然很好奇是否可以让界面包含自定义事件.

这可能吗?或者在这种情况下我是否必须使用C#的EventHandler类?

Dmi*_*nko 7

你为什么不用EventHandler?例如

  // I've added "I" since it's an Interface
  public interface IMenuElement {
    void AddMenuElement(MenuElement menuToAdd);
    void RemoveMenuElement(MenuElement menuToRemove);
    void Activate();

    // I've changed your 
    // MenuElement GetMenuElement(int index)
    // to indexer
    MenuElement this[int index] {get;}

    // Event of interest; I've renamed it from onActivate
    event EventHandler Activated;
  }

  ...
  // Possible interface implementation
  public class MyMenuElement: IMenuElement {
    ...
    // name like "onActivate" is better to use here, as a private context
    private void onActivated() {
      if (Object.ReferenceEquals(null, Activated)) 
        return;

      Activated(this, EventArgs.Empty);
    }

    public void Activate() {
      // Some staff here
      ... 
      // Raising the event
      onActivated();
    }
  }
Run Code Online (Sandbox Code Playgroud)