2011-03-21 54 views
0

我剛開始在C#中使用事件和委託,我不確定這是我應該如何設置的。我的活動設置是否正確和有效?

MenuScreen.cs

public class MenuScreen { 
     public class MenuScreen { 

     public List <MenuEntry> _entries = new List<MenuEntry> {}; 

     public void Initialize() { 
      foreach (MenuEntry entry in _entries) { 
       entry.EntrySelected += onEntrySelected; 
      } 
     } 

     private void onEntrySelected (object sender, MenuEntryEventArgs e) { 
      Debug.WriteLine (e._text); 
     } 
} 

MenuEntry.cs

public class MenuEntry { 
    public delegate void EventHandler (object sender, MenuEntryEventArgs e); 

    public event EventHandler EntrySelected;  

    private ButtonState _clickstate = ButtonState.Released;//Left mouse button state 

    public void Draw (MenuScreen menuscreen, Vector2 position) { 
     if (Mouse.GetState().LeftButton == ButtonState.Pressed) {//If left mouse button is pressed 
      if (_clickstate == ButtonState.Released && bounds.Contains (x, y)) {//If left mouse button isn't already pressed and mouse is in entry hitbox 
       onEntrySelected(); 
      } 

      _clickstate = ButtonState.Pressed;//Left mouse button state is pressed 
     } else {//If left mouse button is released 
      _clickstate = ButtonState.Released;//Left mouse button state is released 
     } 

    protected virtual void onEntrySelected() { 
     EventHandler handler = EntrySelected; 
     MenuEntryEventArgs args = new MenuEntryEventArgs (_text); 

     if (handler != null) { 
      handler (this, args); 
     } 
    } 
} 

我想這一定會更好?我查看了他發佈鏈接的線索,並將其用作指南。

+0

你打破了幾條指導原則,這可能也可能不重要。 'EntrySelected()'應該被聲明爲'internal'。另見http://stackoverflow.com/questions/2448487/how-to-dispatch-events-in-c/2448530#2448530 – 2011-03-21 15:54:21

回答

3

請使用.NET的標準源代碼慣例。代碼更可讀。

public class MenuScreen { 
    // the common pattern for events is method which can event raise 
    // the event-raising methods should have prefix "On-" 
    protected internal virtual void OnEntrySelected(EventArgs e) { 
     // delegates are immutable, so variable "handler" will not be changed 
     var handler = this.EntrySelected; 
     // check for null. null handler can not be raised 
     if (null != handler) { 
      // raise handler 
      handler(this, e); 
     } 
    } 
    // the common pattern for event handler are arguments "sender" and "args". 
    // the public members should start with upper case 
    // the common pattern for events "something happend" is suffix "-ed" 
    public event EventHandler EntrySelected; 
} 

public class MenuEntry { 
    public void Draw(MenuScreen screen, Vector2 position) { 
     // ... some code ... 
     screen.OnEntrySelected(EventArgs.Empty); 
    } 
}