【问题标题】:Error when calling a getter from another From从另一个 From 调用 getter 时出错
【发布时间】:2011-05-13 10:09:23
【问题描述】:

我有两个 From(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();
    }
}

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

【问题讨论】:

    标签: c# .net winforms class forms


    【解决方案1】:

    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 也不是一个描述性很强的名字...)

    【讨论】:

      【解决方案2】:

      问题是您已将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
      }
      

      【讨论】:

        【解决方案3】:

        试试

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

        希望对您有所帮助。

        【讨论】:

          猜你喜欢
          • 2018-02-22
          • 2015-11-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-09-18
          • 2021-09-26
          • 2012-06-04
          • 2019-10-14
          相关资源
          最近更新 更多