How do I persist data without global variables?

后端 未结 5 1027
傲寒
傲寒 2020-12-18 00:06

I\'m used to scripting languages. PHP, Javascript etc. and I\'ve written a few relatively simple Java and C# apps. This is a question I\'ve repeatedly needed an answer for,

5条回答
  •  再見小時候
    2020-12-18 00:40

    Firstly, always ask yourself if you really need to have a global, often you won't. But if you really have to have one...

    The best way to do this is to have a static property on some sensibly named class, it effectively becomes your global variable

    public class Credentials
    {
      public static string Username {get;set;}
    }
    
    //...somewhere in your code
    
    Credentials.Username = "MyUserName";
    

    EDIT:

    A couple people here have said the blanket statement that Global Variables are bad, and I do agree with this sentiment, and it would appear that the designers of C# also agree as they are simply not available.

    We should however look at the reasons why Globals are bad, and they are mostly regarded as bad because you break the rules of encapsulation. Static data though, is not necesarrily bad, the good thing about static data is that you can encapsulate it, my example above is a very simplistic example of that, probably in a real world scenario you would include your static data in the same class that does other work with the credentials, maybe a Login class or a User class or whatever makes sense to your app.

提交回复
热议问题