C# WinForms继承的表单无法看到父项';s变量

C# WinForms继承的表单无法看到父项';s变量,c#,winforms,inheritance,C#,Winforms,Inheritance,我试图在父窗体中使用变量来存储变量。父窗体的代码如下所示: public partial class Form1 : Form { internal string testVar; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { testVar = "button1

我试图在父窗体中使用变量来存储变量。父窗体的代码如下所示:

public partial class Form1 : Form
{
    internal string testVar;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        testVar = "button1";
        MessageBox.Show("testVar = " + testVar);
    }

    private void button2_Click(object sender, EventArgs e)
    {
        Form2 newfrm = new Form2();
        newfrm.Show();
    }
}
public partial class Form2 : Form1
{
    public Form2()
    {
        InitializeComponent();
    }

    private void button3_Click(object sender, EventArgs e)
    {
        MessageBox.Show(base.testVar);
    }
}
因此,如果用户按下button1,它会将变量设置为“button1”。按下按钮2启动子窗体,定义如下:

public partial class Form1 : Form
{
    internal string testVar;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        testVar = "button1";
        MessageBox.Show("testVar = " + testVar);
    }

    private void button2_Click(object sender, EventArgs e)
    {
        Form2 newfrm = new Form2();
        newfrm.Show();
    }
}
public partial class Form2 : Form1
{
    public Form2()
    {
        InitializeComponent();
    }

    private void button3_Click(object sender, EventArgs e)
    {
        MessageBox.Show(base.testVar);
    }
}

因此,button3显示父窗体中内部变量的值。但是,它是空的(无论是否设置)。为什么子窗体看不到父窗体中的值?

因为父窗体和子窗体的实例都有自己的副本

这应该起作用(并加以解释):


这是两个不同的例子。一个是主窗体,是Form1的一个实例,它将
testVar
变量设置为一个值。另一个是二级表单,一个从Form1派生的Form1实例,但未设置其
testVar
变量。

您的代码不访问父表单!您正在使用
base.testVar
,它访问从base类继承的当前对象中的变量,而不是从创建
Form2
实例的
Form1
实例中继承的变量

也许你想要以下的东西:

public partial class Form1 : Form
{
    ...
    private void button2_Click(object sender, EventArgs e)
    {
        Form2 newfrm = new Form2();
        newfrm.ParentForm = this;
        newfrm.Show();
    }
}

public partial class Form2 : Form1
{
    public Form2()
    {
        InitializeComponent();
    }

    private void button3_Click(object sender, EventArgs e)
    {
        string v = (ParentForm != null) ? ParentForm.testVar : "<no parent set>";
        MessageBox.Show(v);
    }
    public Form1 ParentForm;
}
公共部分类表单1:表单
{
...
私有无效按钮2\u单击(对象发送者,事件参数e)
{
Form2 newfrm=新Form2();
newfrm.ParentForm=此;
newfrm.Show();
}
}
公共部分类Form2:Form1
{
公共表格2()
{
初始化组件();
}
私有无效按钮3\u单击(对象发送者,事件参数e)
{
字符串v=(ParentForm!=null)?ParentForm.testVar:;
MessageBox.Show(v);
}
公共表格1家长表格;
}

(好的,您的
父窗体需要更好的保护)

您确定在
窗体2
的实例中为
testVar
分配了一些内容吗?