1. Static members
1. Modification through static keywords is a class and instance members belong to the object. When this class is loaded for the first time, all static members under this class will be loaded.
2. Static members are only created once, so there is only one static member, and the instance members have as many objects as they have.
3. When the class is loaded, all static members will be created in the "static storage area". Once created, they will not be recycled until the program exits.
Note: Person p;// This way it is actually loaded.
4. When variables need to be shared and methods need to be called repeatedly, these members can be defined as static members.
5. In static methods, instance members cannot be called directly, because when the static method is called, the object may not exist.
6. The this/base keyword cannot be used in static methods because it is possible that the object does not exist yet.
7. You can create an object of this class and formulate the members of the object to operate in a static method.
8. In the instance method, static members can be called because static members must exist at this time.
2. The difference between static members and instance members
1. The life cycle is different.
2. The storage locations in memory are different.
3. Static class
1. Classes modified by static keywords.
2. Only static members can be declared in static classes.
3. The essence of a static class is an abstract sealed class, so it cannot be inherited or instantiated.
4. If all members under a class need to be shared, then this class can be defined as a static class.
4. Static constructor
1. The members of this class will execute a static constructor before the first time they are accessed.
2. The static constructor is executed only once.
Eg:
class Program
{
public static int i =0;
public Program()
{
i = 1;
("Instance constructor is called");
}
static Program()
{
i = 2;
("The static constructor is executed");
}
static void Main(string[] args)
{
();//The result is 2. First, the class is loaded, and all static members are created in the static storage area. i=0, and then the class members are called. At this time, the static constructor will be called, i=2
Program p = new Program();
();//The result is 1. After the strength is increased, the instance constructor is called, i=1. Since the static constructor is only executed once, it will not be executed again.
}
}