“Global variable” in Visual C#

旧时模样 提交于 2019-12-02 03:17:22

Give the forms a reference to the Graph in their constructor.

 Graph g = new Graph();
 Form1 f1 = new Form1(g);
 Form2 f2 = new Form2(g);

Then both forms are working with the same graph.

Make a static class. The variables that need global access, put them inside that class.

Even better idea would be to use Singleton objects to represent globally accessible objects.

Make your Graph instance a public static member of a static class and for all practical purposes you have your global.

Take a look at the Singleton pattern for one possible approach to having a common object:

Singleton Pattern

C# has static fields for this. You can use SIngleton pattern in conjunction with static field. But don't forget that misusage of application-wide objects can bring down your design.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!