【问题标题】:Form inheritance should be abstract表单继承应该是抽象的
【发布时间】:2015-10-01 04:48:57
【问题描述】:

这是我的代码

GeneralLesson.cs:它只是一个 .cs 文件,没有 .Designer.cs 或 .resx 文件

public /*abstract*/ class GeneralLesson : Form
{
    public GeneralLesson()
    {
        this.StartPosition = SS.FrmStartPos;//If I want to change it later, I just change it here and all the children will get the change
    }
    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        base.OnFormClosing(e);
        if (e.CloseReason == CloseReason.WindowsShutDown) return;

        SS.LearningDay = 0; //SS is my static class that hold the static variables.
        SS.FrmMain.Show();
    }
}

SentLesson.cs:这实际上是一个windows窗体,有.Designer.cs和.resx文件

public partial class _Sent_Lesson : GeneralLesson
{
    public _Sent_Lesson()
    {
        InitializeComponent();           
        richTextBox1.Text = "under construction";
    }

}

所以它实际上很好地满足了我的目的。我的 SentLesson 窗口继承了 GeneralLesson 的构造函数和 OnFormClosing。但问题是我不能再设计我的 SentLesson 窗口了,如下图所示:

也许我做错了。但我不想将 GeneralLesson 创建为 Window,因为我没有在其上设计任何控件,我只想覆盖一些函数,如 OnFormClosing 或构造函数。有什么办法可以在不将 GeneralLesson 作为窗口的情况下做到这一点。

感谢阅读。

【问题讨论】:

  • 什么是SS?抛出异常的细节是什么?您的问题标题说“应该是抽象的”,但我在您的问题中看不到任何 abstract 类型。请注意,abstract 类型不能与 WinForms 设计器一起使用。
  • @Dai SS 是我保存静态变量的静态类。我在我的代码中评论它。一开始,我将一般课程创建为“公共抽象类 GeneralLesson:Form”,但后来我将其更改为“公共类 GeneralLesson:Form”——无论如何,还是会出现错误页面。并且抛出异常不是来自我的代码,这是因为 Visual Studio 无法加载设计器。

标签: forms inheritance overriding abstract


【解决方案1】:

我终于找到了解决方案。尽管抽象父窗体仍然可以在逻辑上工作,但子窗体无法使用 Visual Studio 设计器进一步设计。所以我必须以 Visual Studio 的方式继承表单。

如您所见,Visual Studio 为我们提供了 Inherited Form 来创建 Children 表单。因此,我将 GeneralLesson.cs 创建为 Windows 窗体,并将 SentLesson.cs 创建为继承窗体。所以 SentLesson 继承了 GeneralLesson 的构造函数和 OnFormClosing,SentLesson 的设计器不再报错。

如果您希望子窗体可以从父窗体访问某些控件,例如父窗体的“按钮 A”。只需将属性窗口中父级的“按钮 A”的修饰符从私有设置为受保护。然后,您可以使用子窗体中的按钮 A 执行任何操作。

感谢您的阅读。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-15
    • 1970-01-01
    • 2012-02-24
    相关资源
    最近更新 更多