Using Events in Interfaces

I am introducing a menu system that uses a composite design pattern. I have the following MenuElement interface:

public interface MenuElement
{
    void AddMenuElement( MenuElement menuToAdd );
    void RemoveMenuElement( MenuElement menuToRemove );
    MenuElement GetMenuElement( int index );
    void Activate();
}

I was thinking of turning on the "OnActivate" event in this interface, so that MenuItems that implement this interface can trigger functions when activated. I tried to implement it as follows:

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

    void AddMenuElement( MenuElement menuToAdd );
    void RemoveMenuElement( MenuElement menuToRemove );
    MenuElement GetMenuElement( int index );
    void Activate();
}

However, the compiler will not let me declare a delegate inside the interface. I know the type of C # event called EventHandler, but unlike my desired MenuEvent, it requires both objects and EventArgs parameters. I also considered moving my event and delegation to MenuItem, but I'm still wondering if it is possible for the interface to include a custom event.

? # EventHandler ?

+4
2

EventHandler? .

  // I've added "I" since it 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();
    }
  }
+3

; (), .

"", . .

public abstract class MenuElement
{
    public delegate void MenuEvent();
    event MenuEvent onActivate;

    abstract virtual void AddMenuElement( MenuElement menuToAdd );
    abstract virtual void Activate();
}

, MenuElement . , , .

, , .

+1

All Articles