【问题标题】:How to properly extend WinForms如何正确扩展 WinForms
【发布时间】:2015-07-09 05:29:37
【问题描述】:

一个常规的 C# Windows 窗体如下所示(非设计者代码):

public partial class BaseForm : Form
{
    public BaseForm()
    {
        // v--- very important method, it is what initializes the form
        InitializeComponent();
    }

    public BaseForm(string title)
        : this() // chain with the main constructor
    {
        this.Text = title;
    }
}

现在让我们创建一个派生形式:

public partial class EntityForm : BaseForm
{
    public EntityForm()
        : base()
    {
    }

    public EntityForm(Entity entity)
        : base(entity.Name)
    {
    }
}

第二种形式停止正常工作。当InitializeComponent(); 被调用时,它是在BaseForm 的上下文中完成的(因为它总是被定义为不可覆盖和私有的)。

乍一看,一个解决方案可能是在每个构造函数中都有InitializeComponent();,但这意味着它可能会被多次调用,从而不必要地创建对象(因为构造函数链接)。 对此的解决方案可能是一般不调用基本构造函数,这有点违背 OOP 的目的。

我做错了什么?有什么想法吗?

【问题讨论】:

  • 您的代码示例显示EntityForm 继承Form。您确定这是一个 实际 工作代码示例吗?如果没有,请发布a good, minimal, complete code example 以可靠地重现问题。
  • 呃,我的错。你是对的。固定。
  • 不调用基本构造函数无论如何都不是一种选择。不清楚您所说的“第二个表单停止正常工作” 是什么意思,但坦率地说,我怀疑它与表单继承或InitializeComponent() 方法有什么关系。如果EntityForm 有一个InitializeComponent() 方法,它应该 在其构造函数中调用它。如果没有好的代码示例,甚至无法知道“停止正常工作”是什么意思,更不用说提供解决方案了。
  • 上面的例子现在应该足够了。引用我自己的问题所在:When InitializeComponent();被调用时,它是在 BaseForm 的上下文中完成的(因为它总是被定义为不可覆盖和私有的)。
  • 构造函数没有返回类型。 public void 毫无意义。

标签: c# winforms oop constructor


【解决方案1】:

一个可能有点优雅的解决方案是根本不向构造函数传递参数——也就是说,只让一个无参数构造函数调用InitializeComponent(),这是任何自定义控件的默认设置。 然后我需要第二种方法来实际设置控件。可以根据需要覆盖此方法。

原始来源的示例修复:

public partial class BaseForm : Form
{
    public BaseForm()
    {
        InitializeComponent();
    }

    public virtual void Initialize(string title)
    {
        this.Text = title;
    }
}

public partial class EntityForm : BaseForm
{
    public EntityForm()
    {
        InitializeComponent();
    }

    public virtual void Initialize(Entity entity)
    {
        base.Initialize(entity.Name); // the 'base' keyword is somewhat redundant
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    相关资源
    最近更新 更多