从另一个From调用getter时出错

时间:2011-05-13 10:09:24

标签: c# .net winforms class forms

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

  

错误1'System.Windows.Forms.Form'不包含'getText1'的定义,并且没有扩展方法'getText1'接受类型'System.Windows.Forms.Form'的第一个参数可以找到(是您缺少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();
    }
}

有什么想法吗?谢谢你的帮助。

3 个答案:

答案 0 :(得分:8)

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

Form2 gen = new Form2();
gen.ShowDialog();
gen.getText1();

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

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

using (Form2 gen = new Form2())
{
    gen.ShowDialog();
    string text = gen.Text1;
}

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

答案 1 :(得分:3)

问题是您已将gen声明为基本类型Form,它没有这样的方法:

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

相反,您需要将其明确定义为类型Form2,或使用var让编译器推断出类型:

private void button1_Click(object sender, EventArgs e)
{
    var gen = new Form2();
    gen.ShowDialog();
    gen.getText1();  // works fine now
}

答案 2 :(得分:2)

尝试

Form2 gen = new Form2();         
gen.ShowDialog();         
gen.getText1();

希望得到这个帮助。