An in depth understanding of static in C

  • 2020-05-19 05:36:10
  • OfStack

1. Static members

1, through the keyword static decoration, is belongs to the class, the instance member belongs to the object, in the first load of this class, all the static members below this class will be loaded.

2, the static member is only created once, so there is only one static member, the instance member has as many objects as there are.

3, class loading, all static members will be created in the "static storage area", 1 created until the program exit, will be recycled.

Note: Person p; // this will actually be loaded.

4. When variables need to be Shared and methods need to be repeatedly called, these members can be defined as static members.

5. In a static method, you cannot call the instance member directly, because the object may not exist when the static method is called.

6. The this/base keyword cannot be used in static methods because it is possible that the object does not yet exist.

7. You can create objects of this class and specify the members of the objects to operate in static methods.

8. In an instance method, you can call a static member, because at this point the static member must exist.

2. Difference between static and instance members

1, life cycle is not the same.

2, the location of storage in memory is not the same.

3. Static class

1. The class modified by the static keyword.

2, static classes can only declare static members.

3, the nature of the static class, is an abstract sealed class, so can not be inherited, can not be instantiated.

4. If all the members of a class need to be Shared, the class can be defined as a static class.

4. Static constructor

1. Members of this class execute static constructors before they are accessed the first time.

2. The static constructor is executed only once.

Eg:


class Program
    {
        public static int i =0;
        public Program()
        {
            i = 1;
            Console.Write(" The instance constructor is called ");
        }
        static Program()
        {
            i = 2;
            Console.Write(" The static constructor is executed ");
        }
        static void Main(string[] args)
        {
            Console.Write(Program.i);// The results for 2 First, the class is loaded and all the static members are created in the static store. i=0, And then the member of the class is called, and then the static constructor is called, i=2
            Program p = new Program();
            Console.Write(Program.i);// The results for 1 , after becoming stronger, the instance constructor is called, i=1 Because the static constructor only executes 1 So it won't be executed again. 
        }
    }


Related articles: