简体   繁体   中英

How can I use method from an class instantiated in another form?

I have an class instaciaded in the Form1 and I want call it Form2 it is possible?

For example:

public TheClass thClass; //member from Form1

/* ... */ 

public void foo() { 
       thClass = new TheClass(...);
} 

Form 2:

public void baa() { 
        Form1 form1 = new Form1();
        form1.thClass.MethodName( .. ) ;
}

I'm getting the following erro when call the .baa() method in Form2 :

Object reference not set to an instance of an object.

What's the best way to do this? ref ? I'm wanting do this not instantiated the thClass again.

I hope this is clear. Thanks in advance.

You are getting this exception because thClass is null - in your example you have to call foo() before using thClass .

Reference type fields are nothing special - they can be accessed like any other public field of a class (and Form1 is a class). In general you will want to use a property instead though and avoid public fields since any change to them will break existing consumers - a property that can only be set by the owning class you could express as

public TheClass SomeClass {get; private set;}

you should call Foo() to initizalize "thClass"....

public void baa() { 
    Form1 form1 = new Form1();
    form1.foo();
    form1.thClass.MethodName( .. ) ;
}

since you initialize the thClass in the foo method, you just invoke the method before you use thClass

public void baa() { 
        Form1 form1 = new Form1();
        form1.foo();
        form1.thClass.MethodName( .. ) ;
}

or you can initialize directly

public void baa() { 
        Form1 form1 = new Form1();
        form1.thClass = new TheClass(...);
        form1.thClass.MethodName( .. ) ;
}

The best way to do it might be to pass the instance of TheClass in Form1 to Form2's constructor.

// Code from Form 1
public partial class Form1 : Form
{
    private TheClass thClass;
    public Form1()
    {
        InitializeComponent();
    }
    public void foo()
    { 
        thClass = new TheClass(...);
    }
    private void button1_Click(object sender, EventArgs e)
    {
        Form2 objForm2 = new Form2(thClass);
        objForm2.Show();
    }
}

// Code From Form 2
public partial class Form2 : Form
{
    private TheClass thClass;
    public Form2(TheClass thCls)
    {
        thClass = thCls;
        InitializeComponent();
    }

    private void baa(object sender, EventArgs e)
    {
        thClass.MethodName( .. );
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM