简体   繁体   中英

Can I use my forms as Static?

My program has multiple forms. Some of these forms would benefit greatly from being able to talk to one another, however if Form1 creates an instance of Form2, Form2 can not call back to Form1, at least not very easily.

Is it acceptable to make my forms static so they can talk to each other without the need to instantiate objects of these classes everywhere?

however if Form1 creates an instance of Form2, Form2 can not call back to Form1, at least not very easily

Yes it can - just make your Form2 instance know about the instance of Form1 , eg through a constructor:

// In Form1
Form2 form2 = new Form1(this);

(Note that if your classes are really called Form1 and Form2 , it would be worth giving them more semantically meaningful names. Reject the temptation to stick with whatever Visual Studio gives you :)

I would strongly advise against using statics just to avoid providing your depenencies directly.

I've never created static forms.. usually I just create some globals for my form instances...

You can also access the other forms though the current form's .Parent property as long as you pass the calling form in the .Show(form) or .ShowDialog(form) methods.

Change the constructor of Form 2 as follows

public Form2(Form form1)
{
   _parentForm = form1;
}

You now have a reference to form1.

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