C # static class, static constructor, static variable,

Source: Internet
Author: User

C # static class, static constructor, static variable,

This article describes static variables, static constructors, and static classes.

 

Static variables

Static variables are located on the stack. They are a global variable generated during the compilation period.

    public class Cow
    {
        public static int count;
        private int id;
        public Cow()
        {
            id = ++count;
        }
    }

 

The client creates two Cow instances and prints the static variable count.

        static void Main(string[] args)
        {
            Console.WriteLine(Cow.count);
            Cow cow1 = new Cow();
            Cow cow2 = new Cow();
            Console.WriteLine(Cow.count);
        }

Result:
0
2

○ The static variable count is available globally before the Cow instance is created.
○ If you use private modification before static, you cannot use "class name. static Field name" to access static fields. However, Global static fields always exist.

 

Stack and stack performance, such:

 

Static Constructor

Add a static constructor to the Cow class.

    public class Cow
    {
        public static int count;
        private int id;
        public Cow()
        {
            id = ++count;
        }
        static Cow()
        {
            count = new Random().Next(100);
        }
    }

 

Both constructors and static constructors assign values to Cow static fields. Now we want to know when the static constructor is triggered. Is it triggered when the constructor is used to create an instance? Will it be triggered when Cow fields or attribute values are set? On the client side, you can print the value of the static field count to know when the static constructor is triggered.

        static void Main(string[] args)
        {
            Cow cow1 = new Cow();
Console. WriteLine ("after the first Cow instance is created, count is:" + Cow. count );
            Cow cow2 = new Cow();
Console. WriteLine ("after the second Cow instance is created, count is:" + Cow. count );
        }

○ The static constructor is triggered when the first Cow instance is created.
○ When creating the second Cow instance, the static constructor is not triggered, but is used to create an instance.
○ The static constructor is executed only once.

 

Therefore, can we conclude that the static constructor is triggered when the first instance is created?

 

Let's think about this problem from another angle. Will a static constructor be triggered when assigning values to fields of the class?

 

Modify the Cow class:

    public class Cow
    {
        public static int count;
        private int id;
        public static int whatever;
        public Cow()
        {
            id = ++count;
        }
        static Cow()
        {
            count = new Random().Next(100);
            whatever = count + 10;
Console. WriteLine ("after the static constructor is triggered, count is:" + Cow. count );
Console. WriteLine ("after the static constructor is triggered, whatever is:" + Cow. whatever );
        }
    }

Modify the client:

        static void Main(string[] args)
        {
            Cow.count = 100;
            Cow cow1 = new Cow();
Console. WriteLine ("after the first Cow instance is created, count is:" + Cow. count );
            Cow cow2 = new Cow();
Console. WriteLine ("after the second Cow instance is created, count is:" + Cow. count );
        }

 

○ The static constructor is triggered before the Cow field is assigned a value.
○ Create a Cow instance. The static constructor will not be triggered again.
○ The static constructor is executed only once.

 

Here, we can draw a conclusion about the timing when the static constructor is triggered: whether it is creating an instance through the constructor or assigning values to fields or attributes of the class, static constructors are triggered before all these actions.

 

Static class

First, create a class, including static and non-static members.

    public class Logger
    {
        private static int logNumber = 0;
        static public void InitializeLogging()
        {
Console. WriteLine ("log initialization ");
        }
        static public void CloseLog()
        {
Console. WriteLine ("log disabled ");
        }
        static public void LogMsg(string msg)
        {
Console. WriteLine ("log number:" + logNumber + ":" + msg );
        }
        public void DoSth()
        {
Console. WriteLine ("I am not a static method ~~ ");
        }
    }

 

On the client, you can call a method either by using "class name. Static Method Name" or by using an instance of the class.

        static void Main(string[] args)
        {
            Logger.InitializeLogging();
Logger. LogMsg ("log recorded ~~ ");
            Logger.CloseLog();
            Logger logger = new Logger();
            logger.DoSth();
        }

 

If you set a class to a static class, it means that all of this class exists on the stack. Therefore, this class cannot contain instance methods or create such instances.

 

Modify the Logger class and remove the instance method.

    public static class Logger
    {
        private static int logNumber = 0;
        static public void InitializeLogging()
        {
Console. WriteLine ("log initialization ");
        }
        static public void CloseLog()
        {
Console. WriteLine ("log disabled ");
        }
        static public void LogMsg(string msg)
        {
Console. WriteLine ("log number:" + logNumber + ":" + msg );
        }
    }

 

On the client, you cannot create a Logger instance. You can only call a method by using "class name. Static Method Name.

        static void Main(string[] args)
        {
            Logger.InitializeLogging();
Logger. LogMsg ("log recorded ~~ ");
            Logger.CloseLog();
        }

 

 

Summary:
○ Static variables are global and on the stack
○ The static constructor is triggered only once. Whether you create an instance through the constructor or assign values to the fields or attributes of the class, the trigger time of the static constructor is before these actions.
○ The static class cannot contain instance members.

 

 


In C language-> what?

-> Is a whole. It is used to point to a struct, class in C ++, and other pointers containing sub-data to obtain sub-data. In other words, if we define a struct in C and declare a pointer pointing to this struct, we need to use "->" to retrieve the data in the struct using the pointer ".
For example:
Struct Data
{
Int a, B, c;
};/* Define struct */
Struct Data * p;/* define struct pointer */
Struct Data A = {1, 2, 3};/* declare variable */
Int x;/* declare a variable x */
P = & A;/* point p to */
X = p-> a;/* indicates that the data item a in the struct pointed to by p is assigned to x */
/* Because p points to A, p-> a = A. a, that is, 1 */

For the first problem, p = p-> next; this should appear in the linked list of C language. next here should be a struct pointer of the same type as p, and its definition format should be:
Struct Data
{
Int;
Struct Data * next;
};/* Define struct */
............
Main ()
{
Struct Data * p;/* declare the pointer Variable p */
......
P = p-> next;/* assign the value in next to p */
}
The linked list pointer is a difficulty in C language, but it is also the key. It is very useful to learn it. To be careful, you must first talk about variables and pointers.
What is a variable? The so-called variables should not be simply thought that the amount will become a variable. Let's use the question of our Dean: "Is the classroom changing ?" Change, because there are different people in the classroom every day, but they do not change, because the classroom is always there, and it does not become larger or smaller. This is the variable: There is a constant address and a variable storage space. Under normal circumstances, we only see the variable in the room, that is, its content, but do not pay attention to the variable address, but the C language pointer is the address of the room. We declare that variables are equivalent to building a house to store things. We can directly watch things in the house, while declaring pointers is equivalent to getting a positioner. When a pointer points to a variable, it is to use the pointer to locate the variable. Then we can use the pointer to find the variable "tracked" and get the content in it.
What about struct? The structure is equivalent to a villa composed of several houses, and several houses are bound for use together. Suppose there are many such villas distributed in a big maze, and each villa has a house. The location information of another villa is put in it. Now you have found the first villa with the positioner and obtained what you want from it (the data part of the linked list ), then, calculate the location of the next villa into your positioner (p = p-> next), and go down to the next villa ...... If you go on like this, you will know that the information of a villa on the ground is gone (p-> next = NULL), and your trip is over. This is the process of traversing a linked list. Now you can understand the meaning of p = p-> next!
Write so much. I hope you can understand.
If you want to learn c and C ++ well, you must be familiar with linked lists and pointers!

In C language-> what?

-> Is a whole. It is used to point to a struct, class in C ++, and other pointers containing sub-data to obtain sub-data. In other words, if we define a struct in C and declare a pointer pointing to this struct, we need to use "->" to retrieve the data in the struct using the pointer ".
For example:
Struct Data
{
Int a, B, c;
};/* Define struct */
Struct Data * p;/* define struct pointer */
Struct Data A = {1, 2, 3};/* declare variable */
Int x;/* declare a variable x */
P = & A;/* point p to */
X = p-> a;/* indicates that the data item a in the struct pointed to by p is assigned to x */
/* Because p points to A, p-> a = A. a, that is, 1 */

For the first problem, p = p-> next; this should appear in the linked list of C language. next here should be a struct pointer of the same type as p, and its definition format should be:
Struct Data
{
Int;
Struct Data * next;
};/* Define struct */
............
Main ()
{
Struct Data * p;/* declare the pointer Variable p */
......
P = p-> next;/* assign the value in next to p */
}
The linked list pointer is a difficulty in C language, but it is also the key. It is very useful to learn it. To be careful, you must first talk about variables and pointers.
What is a variable? The so-called variables should not be simply thought that the amount will become a variable. Let's use the question of our Dean: "Is the classroom changing ?" Change, because there are different people in the classroom every day, but they do not change, because the classroom is always there, and it does not become larger or smaller. This is the variable: There is a constant address and a variable storage space. Under normal circumstances, we only see the variable in the room, that is, its content, but do not pay attention to the variable address, but the C language pointer is the address of the room. We declare that variables are equivalent to building a house to store things. We can directly watch things in the house, while declaring pointers is equivalent to getting a positioner. When a pointer points to a variable, it is to use the pointer to locate the variable. Then we can use the pointer to find the variable "tracked" and get the content in it.
What about struct? The structure is equivalent to a villa composed of several houses, and several houses are bound for use together. Suppose there are many such villas distributed in a big maze, and each villa has a house. The location information of another villa is put in it. Now you have found the first villa with the positioner and obtained what you want from it (the data part of the linked list ), then, calculate the location of the next villa into your positioner (p = p-> next), and go down to the next villa ...... If you go on like this, you will know that the information of a villa on the ground is gone (p-> next = NULL), and your trip is over. This is the process of traversing a linked list. Now you can understand the meaning of p = p-> next!
Write so much. I hope you can understand.
If you want to learn c and C ++ well, you must be familiar with linked lists and pointers!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.