开发者

Global variable in a static method

开发者 https://www.devze.com 2022-12-20 04:24 出处:网络
This seems basic but Im finding this quite trivial.Simply how would you recommend setting a global variable with a static class (i.e. console-application)?

This seems basic but Im finding this quite trivial. Simply how would you recommend setting a global variable with a static class (i.e. console-application)?

To give you a little more background the main method is calling some custom eventhandlers that I hope to get / set开发者_C百科 the variables.

Any ideas or suggestions you have is appreciated.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消