c# - 表单按钮事件和表单类继承
问题描述
我创建了一个表格。例如,一些表单事件方法如下所示:
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
该类?
解决方案
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
}
推荐阅读
- c# - 从 C# 8 中的 System.Reflection.Metadata 获取接口可为空的上下文元数据
- amazon-web-services - AWS ECS 私有和公共服务
- laravel-5 - 使用 vuetable-2 从我的数据库中的表中行数据
- c++ - 由 ref 传递给函数的向量被自动解除分配
- keras - compute_output_shape 中的 Keras API 模型引发 NotImplementedError NotImplementedError
- reactjs - 如何在 md 断点上使用 reactstrap 以该顺序垂直堆叠左、右和中心列?
- sql-server - 为什么十进制数在我的数据库中始终为 0?
- java - 给定计算的程序给出错误的输出
- c# - 有条件地从响应或最佳实践中排除模型字段以实现它?
- c# - 将字符串转换为 sql 查询