C# Winforms,将父对象分配给新的子对象,而不是实例化表单

C# Winforms, assigning parent to new child object, other than instantiating form

我有一个带有两个子窗体的 MDI 容器。我们被教导(并且 MSDN 文档仅给出了示例)使用关键字 'this',它假定所讨论的子对象是从 MDI 容器本身创建的。

如果我在 MDI 容器中创建对象,这将是正确的:

Form_Child2 child = new Form_Child2(textBox1.Text);
child.MdiParent = this;
child.Show();

相反,我正在尝试做一些更像:

Form_Child2 child = new Form_Child2(textBox1.Text);
child.MdiParent = Form_Parent;
child.Show();

然而,这会抛出一个错误,指出 "Form_Parent" 是一个类型,不能用作变量。我想我隐约明白它的意思,但还不清楚。我也尝试研究了关键字 'this',但仍然卡住了。

这是因为您正试图将 Type 设置为父级

您需要先实例化该类型,然后再将其设置为父级:

Form_Parent parent = new Form_Parent();
Form_Child2 child = new Form_Child2(textBox1.Text);
child.MdiParent = parent;
child.Show();

当然,如果你的parent已经创建了,你需要将Parent设置为那个实例,而不是创建一个新的。

如果您不知道 Instance、Object 和 Class 是什么意思,我建议您阅读 Object Oriented Programmation

如果您想成为一名 C# 程序员,了解类型和对象之间的区别非常重要。是的,这里有大问题,这里需要 Form_Parent 的实例,不能使用类型名称。

只有 一个 MDI 父实例 window。这是您可以利用的东西,您可以将静态 属性 添加到父 class。让它看起来像这样:

public partial class Form_Parent : Form {

    public static Form_Parent Instance { get; private set; }

    public Form_Parent() {
        InitializeComponent();
        Instance = this;
    }
    // etc..
}

现在就很简单了:

Form_Child2 child = new Form_Child2(textBox1.Text);
child.MdiParent = Form_Parent.Instance;
child.Show()