“Global variable” in Visual C#

前端 未结 5 1173
眼角桃花
眼角桃花 2021-01-23 21:26

I have made the Graph class, and i want to simulate a distribution network. The Graph works 100%. But, i want to use that same struct/class in all my application! For example: I

相关标签:
5条回答
  • 2021-01-23 21:29

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

    0 讨论(0)
  • 2021-01-23 21:30

    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.

    0 讨论(0)
  • 2021-01-23 21:32

    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.

    0 讨论(0)
  • 2021-01-23 21:33

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

    Singleton Pattern

    0 讨论(0)
  • 2021-01-23 21:36

    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.

    0 讨论(0)
提交回复
热议问题