我的活动是否正确有效地设置?

时间:2011-03-21 15:47:31

标签: c# event-handling xna

我刚开始在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);
        }
    }
}

我认为这一定更好?我查看了他发布链接的帖子并将其用作指南。

1 个答案:

答案 0 :(得分: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 );
    }
}