C# Static variables - scope and persistence

前端 未结 9 971
一向
一向 2020-11-27 05:38

I just did a little experiment:

public abstract class MyClass
{
  private static int myInt = 0;

  public static int Foo()
  {
    return myInt;
  }

  publi         


        
相关标签:
9条回答
  • 2020-11-27 06:01

    They will persist for the duration of AppDomain. Changes done to static variable are visible across methods.

    MSDN:

    If a local variable is declared with the Static keyword, its lifetime is longer than the execution time of the procedure in which it is declared. If the procedure is inside a module, the static variable survives as long as your application continues running.

    See following for more details:

    • C#6 Language Specification - Static Variables
    • C#6 Language Specification - Application Startup
    • MSDN: Static Variable
    • MSDN: Variable Lifetime
    0 讨论(0)
  • 2020-11-27 06:05

    If it's a static variable, that means it exists exactly one place in memory for the duration of the program.

    0 讨论(0)
  • 2020-11-27 06:06

    It persist for duration of the program execution, or until you overwrite it with another value. If you want to make the result as what you want it to be, you should specify myInt = 0 in the constructor before return myInt;

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