2

在 C# 中,事件只能由所属类通过受保护的虚拟方法(如 OnClick、OnExit 等)触发……我正在尝试为我的一些复杂类实现 GOF 状态模式。到目前为止一切都很好,除了我找不到从我的状态类中触发拥有类的事件的方法。

例如,我的按钮有两种状态(向上和向下),DownState 类将检查用户输入,并在必要时触发按钮的 Click 事件。

public class Button
{
    public Button()
    {
        State = new ButtonStateNormal(this);
    }

    public event EventHandler<MouseEventArgs> Click;
    public ButtonState State { get; set; }

    protected virtual void OnClick(MouseEventArgs e)
    {
        if (Click != null)
            Click(this, e);
    }
}

public class ButtonStateNormal : ButtonState
{
    Button button;
    public ButtonStateNormal(Button button)
    {
        this.button = button;
    }

    public override void CheckForInput()
    {
        //...
        //Check for user input and change the state
        //...
        button.State = new ButtonStateDown(button);
    }
}

public class ButtonStateDown : ButtonState
{
    Button button;
    public ButtonStateDown(Button button)
    {
        this.button = button;
    }

    public override void CheckForInput()
    {
        //...
        //Check for user input, fire the event of the button and change the state
        //...
        button.OnClick(new MouseEventArgs(mouse.X, mouse.Y)); //I want to do this, obviously it won't work this way
        button.State = new ButtonStateNormal(button);
    }
}

我怎样才能做到这一点?

4

1 回答 1

2

在您的班级上设置一个事件或委托ButtonState,以便您的按钮可以调用。State将您的自动属性更改Button为具有后备存储的属性,该后备存储在状态更改时挂钩和取消挂钩 this 事件或委托。

public class Button
{
    public Button()
    {
        State = new ButtonStateNormal(this);
    }
    private ButtonState _state;
    public event EventHandler<MouseEventArgs> Click;
    public ButtonState State
    {
        protected get
        {
            return _state;
        }
        set
        {
            if (_state == value)
                return;
            if (_state != null)
                _state.Click -= OnClick;
            if (value != null)
                value.Click += OnClick;

            _state = value;

        }
    }

    protected virtual void OnClick(MouseEventArgs e)
    {
        if (Click != null)
            Click(this, e);
    }

    public void CheckForInput(){
        State.CheckForInput();
    }
}

public abstract class ButtonState
{
    public abstract void CheckForInput();
    public ClickDelegate Click;
    public delegate void ClickDelegate(MouseEventArgs a);
}

然后您可以在具体的 State 类中执行此操作

public class ButtonStateDown : ButtonState
{
    Button button;
    public ButtonStateDown(Button button)
    {
        this.button = button;
    }

    public void CheckForInput()
    {
        //...
        //Check for user input, fire the event of the button and change the state
        //...
        if(Click != null)
            Click(new MouseEventArgs(mouse.X, mouse.Y))
        button.State = new ButtonStateNormal(button);
    }
}
于 2013-03-09T04:46:05.997 回答