首页 > 解决方案 > 表单按钮事件和表单类继承

问题描述

我创建了一个表格。例如,一些表单事件方法如下所示:

private void BtnClose_Click(object sender, EventArgs e)
{
    this.Close();
}

private void BtnRun_Click(object sender, EventArgs e)
{
    this.Run();
}

private void BtnReset_Click(object sender, EventArgs e)
{
    using (SqlConnection conn = new SqlConnection(Program.ConnStr))
    {
        using (SqlCommand cmd = conn.CreateCommand())
        {
            conn.Open();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "rt_sp_testAOFreset";
            result = cmd.ExecuteNonQuery();
        }
    }
}

看起来简单明了,但我实际上是将表单继承到另一个类中。

   public class Simulate : TableForm

所以,当我实例化Simulate类时......

    Simulate sim = new Simulate();
    Application.Run(sim);

Simulate当按钮来自类时,如何运行来自类的方法TableForm?例如,表单有一个“运行”按钮,其中事件方法包含在TableForm类中,但运行方法实际上在Simulate类中。

方法可以移动到Simulate类吗?还是可以Simulate由作为基类的类调用TableForm该类?

标签: c#

解决方案


TableForm 类可能会在其 InitializeComponent() 方法中将这些按钮添加到表单中。假设派生的 Simulate 类的构造函数调用其基类的构造函数,这些相同的控件将添加到您的派生表单中。

public class Simulate: TableForm{
    ...
    public Simulate() : base() {
        InitializeComponent();
    }
    ...
}

我不确定您的事件处理程序是在哪里添加的,但只要您正确调用基类构造函数和加载例程,就会设置相同的事件处理程序(除非您在其他地方设置了控件)。如果您想覆盖这些例程的功能,请将它们设置为protected virtual

更好的是,添加可以覆盖的受保护虚拟 OnRun 和 OnReset 方法(现有的受保护虚拟例程可以为 OnClose 和 OnClosing 覆盖)。

注意:我假设您使用的是 WinForms

编辑:根据要求,这是一些示例代码。像这样设置 TableForm:

private void BtnClose_Click(object sender, EventArgs e)
{
    this.Close();
}

private void BtnRun_Click(object sender, EventArgs e)
{
    this.Run();
} 

protected virtual void Run() {
    // do stuff
}

private void BtnReset_Click(object sender, EventArgs e)
{
    Reset();
}

protected virtual void Reset() {
    using (SqlConnection conn = new SqlConnection(Program.ConnStr))
    {
        using (SqlCommand cmd = conn.CreateCommand())
        {
            conn.Open();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "rt_sp_testAOFreset";
            result = cmd.ExecuteNonQuery();
        }
    }
}

现在在派生的 Simulate 类中,您可以这样做:

protected override void Run() {
    base.Run(); 
    // additional stuff
} 

protected override void Reset() {
    base.Reset();
    // additional stuff
}

protected override void OnFormClosing(System.Windows.Forms.FormClosingEventArgs e) {
    // handle the form closing event
}

推荐阅读