C# Static variables - scope and persistence

前端 未结 9 970
一向
一向 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 05:44

    Your changes in static scope will live as long as your app

    0 讨论(0)
  • 2020-11-27 05:46

    Per the C# spec, a static variable will be initialized no later than the first time a class is loaded into an AppDomain, and will exist until that AppDomain is unloaded - usually when the program terminates.

    0 讨论(0)
  • 2020-11-27 05:51

    They persist "for the lifetime of the application domain in which your program resides" according to Microsoft Docs: Static Classes and Static Class Members (C# Programming Guide).

    See also:

    • Microsoft Docs: Application Domains

    • .NET API Browser: AppDomain Class

    0 讨论(0)
  • 2020-11-27 05:53

    The results I expected were 0, 3, 0, 10, 0.

    To my surprise, I got 0, 3, 3, 10, 10.

    I'm not sure why you would expect the static variable to revert back to its original value after being changed from within the Foo(int) method. A static variable will persist its value throughout the lifetime of the process and only one will exist per class, not instance.

    0 讨论(0)
  • 2020-11-27 05:54

    For the duration of the program execution.

    Static class variables are like globals. They're not connected to specific objects of a class - there's only one instance of those per program. The only variables that live during function execution time are automatic (local) variables of the function.

    0 讨论(0)
  • 2020-11-27 05:59

    Static variables belong to type, not to its instance. And usually (if you are not creating multiple app domains) type objects are loaded only once and exist during the lifetime of the process.

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