从类中调用方法

use*_*ser 3 c# methods class nullreferenceexception

我有2个表单(Form1和Form2)和一个类(Class1).Form1包含一个按钮(Button1),Form2包含一个RichTextBox(textBox1)当我在Form1上按下Button1时,我想要调用方法(DoSomethingWithText).我一直得到"NullReferenceException - 对象引用未设置为对象的实例".这是一个代码示例:

Form1中:

namespace Test1
{  
    public partial class Form1 : Form  
    {
        Form2 frm2;

        Class1 cl;

        public Form1()  
        { 
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            frm2 = new Form2(); 
            cl.DoSomethingWithText();
            frm2.Show()
        } 
   }  
}  
Run Code Online (Sandbox Code Playgroud)

1类:

namespace Test1
{
      class Class1
      {
           Test1.Form2 f2;
           public void DoSomethingWithText()
           {
                f2.richTextBox1.Text = "Blah blah blah";
           }
      }
}
Run Code Online (Sandbox Code Playgroud)

如何在课堂中调用此方法?任何帮助是极大的赞赏.

Ray*_*sen 11

你必须实例化c1f2.试试这个:

public partial class Form1 : Form  
{
    Form2 frm2;
    Class1 cl;
    public Form1()  
    {  
        c1 = new Class1();
        InitializeComponent();  
    }
    private void button1_Click(object sender, EventArgs e)
    {
      frm2 = new Form2();
      cl.DoSomethingWithText(frm2);
      frm2.Show();
    } 
}

class Class1
{

    public void DoSomethingWithText(Test1.Form2 form)
    {
        form.richTextBox1.Text = "Blah blah blah";
    }
}
Run Code Online (Sandbox Code Playgroud)

UPDATE

正如Keith指出的那样,因为你正在实例化一个新版本Form2,所以富文本框永远不会显示等等等等.我已更新样本以解决此问题.