“全局变量”在视觉 C# 中
我已经制作了 Graph 类,我想模拟一个分发网络。 该图 100% 有效。但是,我想在我的所有应用程序中使用相同的结构/类! 例如: 我有显示模拟的 Form1,但我想插入节点(例如),但我想在 Form2 中执行此操作! 由于数据始终位于同一个类中,因此我可以将 Graph 实例设置为全局的,但 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
制作一个静态类。需要全局访问的变量,将它们放在该类中。
更好的主意是使用 Singleton 对象来表示全局可访问的对象。
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.
在表单的构造函数中为表单提供对图表的引用。
然后两种形式都使用同一个图表。
Give the forms a reference to the Graph in their constructor.
Then both forms are working with the same graph.
使您的 Graph 实例成为静态类的公共静态成员,并且出于所有实际目的,您拥有全局。
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# 为此提供了静态字段。您可以将 SIngleton 模式与静态字段结合使用。但不要忘记,滥用应用程序范围的对象可能会破坏您的设计。
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.