How to declare a variable for global use

谁说胖子不能爱 提交于 2019-12-06 05:00:38

Avoid global variables and static keyword at all unless you 100% sure there is no other address your solution (sometimes you might be forced to use statics typically with legacy code hot fixes).

  1. Statics/globals make tight code coupling
  2. Breaks OOD principles (Typically Dependency Injection, Single Responsibility principles)
  3. Not so straightforward type initialization process as many think
  4. Sometimes makes not possible to cover code by unit test or break ATRIP principles for good tests (Isolated principle)

So suggestion:

  1. Understand Problem in the first place, roots, what are you going to achieve
  2. Review your design

you can do this insted

App.Current.Properties["valueTobestored"] = valueTobestored;

And later access it like

string mystoredValue = Convert.ToString(App.Current.Properties["valueTobestored"]); 

It is possible to create a variable for global use. Just create static field or property:

public static class YourStorage
{
   public static object Storage1;
   public static string StringStorage;
} 

And wherever you want, you can just set or get values from that storage:

public class AnotherClass
{
   private void GetDataFromStorage()
   {
      string getValue=YourStorage.StringStorage; 
   }
   private void SetDataFromStorage()
   {
       YourStorage.StringStorage="new value"; 
   }  
}

To create a "global variable", it should be public and static, and declared in a public static class. In .NET it's a common way to declare constants (e.g. Math.PI), but they're not variables!

public static class EveryoneCanSeeMe
{
    public static object EveryOneCanModifyMe;
}

non-public variables are only visible in classes or methods where they're declared.

ps: using global variables is very bad.

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