English 中文(简体)
"Global variable" in Visual C#
原标题:

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 have Form1 that shows the simulation, but i want to insert Nodes (for example) but i want to do it in Form2! Since the data is always in the same class, i could make my Graph instance global but C# does not take global variables. So, how would i solve this? Any ideas? Thank you!

最佳回答

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.





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签