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);
}
}
}
我想這一定會更好?我查看了他發佈鏈接的線索,並將其用作指南。
你打破了幾條指導原則,這可能也可能不重要。 'EntrySelected()'應該被聲明爲'internal'。另見http://stackoverflow.com/questions/2448487/how-to-dispatch-events-in-c/2448530#2448530 – 2011-03-21 15:54:21