Правильно и эффективно ли организовано мое мероприятие? - PullRequest
0 голосов
/ 21 марта 2011

Я только что начал использовать события и делегаты в 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 Ответ

3 голосов
/ 21 марта 2011

Пожалуйста, используйте стандартные соглашения исходного кода для .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 );
    }
}
...