从类中调用方法

时间:2009-07-21 07:47:37

标签: c# class methods 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()
        } 
   }  
}  

的Class1:

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

如何在课堂中调用此方法?非常感谢任何帮助。

5 个答案:

答案 0 :(得分: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";
    }
}

<强> 更新

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

答案 1 :(得分:3)

在尝试使用它之前,您尚未实例化Class1的实例

你需要这样做:

private void button1_Click(object sender, EventArgs e)
{
    c1 = new Class1();
    frm2 = new Form2();
    cl.DoSomethingWithText(frm2);
    frm2.Show();
} 

不是我还在将frm2传递给DoSomethingWithText方法时添加它然后使用(否则你最终会得到另一个类似的异常,因为f2尚未在该类中实例化。

答案 2 :(得分:1)

你永远不会初始化cl(或f2)。

答案 3 :(得分:1)

首先实例化(请参阅@Ray Booysen的回答)或将其转换为静态方法:

class Class1
{
   public static void DoSomethingWithText( Test1.Form2 f2 )
   {
      f2.richTextBox1.Text = "Blah blah blah";
   }
}

然后:

 frm2 = new Form2();
 Class1.DoSomethingWithText( frm2 );
 frm2.Show();

答案 4 :(得分:0)

您需要将DoSomethingWithText声明为静态类或实例化对Class1的引用。

public static void DoSomethingWithText()           
  {                
    //Code goes here;           
  }