从类中调用方法 [英] Calling a method from within a Class

查看:64
本文介绍了从类中调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have 2 Forms (Form1 and Form2) and a class (Class1). Form1 contains a button (Button1) and Form2 contains a RichTextBox (textBox1) When I press Button1 on Form1, I want the method (DoSomethingWithText) to be called. I keep getting "NullReferenceException - Object reference not set to an instance of an object". Here is a code example:

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";
           }
      }
}

如何在类中调用此方法?任何帮助,我们将不胜感激.

How can I call this method from within a class? Any help is greatly appreciated.

推荐答案

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

You have to instantiate c1 and f2. Try this:

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";
    }
}

UPDATE

UPDATE

正如Keith指出的那样,因为您要实例化Form2的新版本,所以丰富文本框将永远不会显示出这样的代码.我已经更新了示例以解决此问题.

As Keith has pointed out, because you're instantiating a new version of Form2, the rich textbox will never show the blah blah blah code. I've updated the sample to fix this.

这篇关于从类中调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆