从另一个From调用getter时出错

Was*_*RAR 0 .net c# forms class winforms

我有两个Froms(Form1,Form2),当我尝试从Form1类调用Form2的公共函数时,我收到此错误.

错误1'System.Windows.Forms.Form'不包含'getText1'的定义,并且没有可以找到接受类型'System.Windows.Forms.Form'的第一个参数的扩展方法'getText1'(你错过了吗? using指令或程序集引用?)C:\ Users ...\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs 24 17 WindowsFormsApplication1.

  public partial class Form1 : Form
  {

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form gen = new Form2();
        gen.ShowDialog();
        gen.getText1(); // I'm getting the error here !!!
    }
}

public partial class Form2 : Form
{
    public string Text1;

    public Form2()
    {
        InitializeComponent();
    }

    public string getText1()
    {
        return Text1;
    }

    public void setText1(string txt)
    {
        Text1 = txt;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.setText1(txt1.Text);
        this.Close();
    }
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?谢谢你的帮助.

Jon*_*eet 8

编译时类型gen目前只是Form.改变它应该没问题:

Form2 gen = new Form2();
gen.ShowDialog();
gen.getText1();
Run Code Online (Sandbox Code Playgroud)

请注意,这与GUI无关 - 它只是普通的C#.如果您刚刚开始使用C#,我建议您使用控制台应用程序来学习它 - 这样的奇怪程度要少得多,您可以一次学习一件事.

我建议您开始遵循.NET命名约定,根据需要使用属性,并处理表单:

using (Form2 gen = new Form2())
{
    gen.ShowDialog();
    string text = gen.Text1;
}
Run Code Online (Sandbox Code Playgroud)

(即使这样,Text1也不是一个非常具有描述性的名字......)