C#Winforms,将父级分配给新的子对象,而不是实例化表单 [英] C# Winforms, assigning parent to new child object, other than instantiating form

查看:55
本文介绍了C#Winforms,将父级分配给新的子对象,而不是实例化表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an MDI container with two child forms. We've been taught (and the MSDN documentation only gives the example) to use the keyword 'this', which assumes that the child object in question is being created from the MDI container itself.

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

If I were creating the object in the MDI container, this would be correct:

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

相反,我正在尝试做更多类似的事情:

Instead, I'm trying to do something more like:

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

但是,这引发了一个错误,指出"Form_Parent"是一种类型,不能用作变量.我想我隐约了解它的含义,但尚不清楚.我也尝试过研究关键字"this",但仍然存在.

However, this throws an error saying that "Form_Parent" is a type and cannot be used as a variable. I think I vaguely understand what it's getting at, but it's not clear. I've tried studying up on keyword 'this' a bit as well, but still stuck.

推荐答案

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

Understanding the difference between types and objects is super-duper important if you want to be a C# programmer. Yes, big problem here, an instance of Form_Parent is required here, you cannot use the type name.

MDI父窗口只有一个一个实例.您可以利用这一点,可以向父类添加静态属性.使它看起来像这样:

There is only ever one instance of the MDI parent window. Which is something you can take advantage of, you can add a static property to the parent class. Make that look like this:

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()

这篇关于C#Winforms,将父级分配给新的子对象,而不是实例化表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆