Global variables in Visual C#

前端 未结 4 534
花落未央
花落未央 2021-01-21 03:15

How do I declare global variables in Visual C#?

相关标签:
4条回答
  • 2021-01-21 03:40

    How about this

    public static class Globals {
        public static int GlobalInt { get; set; }
    }
    

    Just be aware this isn't thread safe. Access like Globals.GlobalInt

    This is probably another discussion, but in general globals aren't really needed in traditional OO development. I would take a step back and look at why you think you need a global variable. There might be a better design.

    0 讨论(0)
  • 2021-01-21 03:48

    Use the const keyword:

    public const int MAXIMUM_CACHE_SIZE = 100;
    

    Put it in a static class eg

    public class Globals
    {
        public const int MAXIMUM_CACHE_SIZE = 100;
    }
    

    And you have a global variable class :)

    0 讨论(0)
  • 2021-01-21 03:48

    The nearest you can do this in C# is to declare a public variable in a public static class. But even then, you have to ensure the namespace is imported, and you specify the class name when using it.

    0 讨论(0)
  • 2021-01-21 03:52

    A public static field is probably the closest you will get to a global variable

    public static class Globals
    {
      public static int MyGlobalVar = 42;
    }
    

    However, you should try to avoid using global variables as much as possible as it will complicate your program and make things like automated testing harder to achieve.

    0 讨论(0)
提交回复
热议问题