Global variable in a static method

ぃ、小莉子 提交于 2019-12-01 04:29:14

Simplest way is

public static Object MyGlobalVariable;

which creates a public static field. A little better is:

public static Object MyGlobalVariable { get; set; }

Which creates a public static property.

There are no global variables in C#. A variable is always locally-scoped. The fundamental unit of code is the class, and within a class you have fields, methods, and properties.

You can mimic a "global variable" by making a public static field or property in some class, but you shouldn't. C# makes this difficult for a very good reason; global variables are pure evil. They violate several good principles of OO design - encapsulation, loose coupling, and high cohesion, to name just a few.

I realize this is a beginner question, but I think it's because this is a beginner question that it's so important to be saying this. Now is the best time to start learning what tactics are actively discouraged or even dangerous in C#, and using a static field/property as a global variable is about six of them. There are legitimate uses for these constructs, but passing data around from place to place is not one of them.

If two different classes depend upon the same information, then pass the information from the source to the destination. This is usually done either through the constructor or as an argument to the method being called. You should always have one and only one instance that truly "owns" this information; making information "global" means that you can't reason about who or what might be depending on it at any given point in time.

Please consider this, and try to think about other ways you could share the information that you want to store in a global variable (i.e. by providing it as an argument to a constructor or method). If you're not sure, post an example of what you're trying to do and we'll help out.

Not 100% sure but you could try a singleton to hold your variables. Without knowing what you are trying to accomplish it's hard to recommend if this solution wouldn't bite you down the road.

http://www.yoda.arachsys.com/csharp/singleton.html

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