在 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);
}
}
我怎样才能做到这一点?