Summary of some confusing concepts in C # (iii) --------- structure, GC, static member, static class

Source: Internet
Author: User

1. Structure in C #

In C #, you can use the struct keyword to define a structure, the level is consistent with the class, written under the namespace.

1) Properties, fields, methods and constructors can be defined in the structure. The sample code is as follows:

// Define the structure
    struct Point
    {

        // Define the field
        private int x;

        // Package field
        public int X
        {
            get {return x;}
            set {x = value;}
        }

        // define method
        public void Result ()
        {

        }

        // Define the constructor
        public Point (int n)

        {
            this.x = n;
            //Console.WriteLine(n);
        }

    }
So, what are the differences between declaring classes and structures?

① In any case, the C # compiler will generate a parameterless constructor for the structure;

When we explicitly define a parameterless constructor, an error will be reported at compile time. The results are as follows:



The compiler tells us that the structure cannot contain an explicit parameterless constructor

But when writing code like this, the compiler does not report an error, the code is as follows:

 // The parameterless constructor can be called here
            Point p = new Point ();
            Console.WriteLine (p.GetType ());
The results are as follows:



Although the structure cannot explicitly declare a parameterless constructor, the programmer can explicitly call the structure's parameterless constructor, indicating that the C # compiler will generate a parameterless constructor for the structure anyway.

② Fields in the structure cannot be assigned initial values;



③ In the constructor of the structure, each field of the structure must be assigned a value;

When we are not talking about explicit constructors, we can not assign values to member fields, but once the constructor is declared, we must assign values to all member fields



To assign values to all member fields, the code is as follows:

// Define the constructor
        public Point (int n)
        {
            this.x = n;
            //Console.WriteLine(n);
        }
④ Assignment of attributes in the constructor is not considered to assign values to fields, and attributes do not necessarily operate on fields;



So when we assign initial values to the fields in the constructor, the correct code should be

         // Define the constructor
        public Point (int n)
        {
            // The correct value can be assigned to the field
            this.x = n;

            // Assign values to properties in the constructor, but not necessarily manipulate fields
            this.X = n;
            //Console.WriteLine(n);
        }
2) The numerical type of the structure

The structure in C # is a value type, and its object and member fields are allocated on the stack, as shown below:



So when we wrote the following code, what happened in the memory?

// The parameterless constructor can be called here
            Point p = new Point ();
            // Assign the value of p
            p.X = 100;
            // Assign p to Point's new object p1
            Point p1 = p;
What happened to Point p1 = p? details as following:



Declare the structure object without using the "new" keyword. If you do not use the "new" keyword to declare the structure object, because the constructor is not called, this time the structure object has no value. The constructor of the structure must assign values to all fields of the structure, so when creating a structure object through the "new" keyword, this object is initialized by the constructor and has a default initial value. The example code is as follows:

class Program
    {
        static void Main (string [] args)
        {
           // There is no way to call the default constructor initialization
            Point p;
            Console.WriteLine (p);

            // It will call the default constructor to initialize the Point object
            Point p1 = new Point ();
            Console.WriteLine (p1);
            Console.ReadKey ();

        }
    }
    // Define the structure
    struct Point
    {
        // The initial value is assigned when defined, the compiler will report an error
        private int x;
    }
Errors will be reported during compilation:



3) The structure cannot use automatic attributes

When I wrote the automatic attribute in the first article, I decompiled the source code and knew that the automatic attribute would generate a default field. In the constructor of the structure, you need to assign a value to each field, but the compiler does not know the name of the field. Therefore, there is no way to use automatic attributes.

So when do you define a class and when do you define a structure?

First of all, we all know that the access speed of the stack is relatively fast compared to the heap. But the stack space is relatively small compared to the heap.

①When we want to represent a lightweight object, we can define the structure and improve the access speed.

②Choose according to the influence of passing value, define the class when the reference to be passed, and define the structure when the copy is to be passed.

Second, about GC (.NET garbage collection)

1) The space variable allocated in the stack will be immediately recovered by the CLR once it goes out of scope; the following code:

        // When defining the value type n, the space occupied by n in the stack will be immediately recovered by the CLR after the program exits the main function
        static void Main (string [] args)
        {
            int n = 5;
            Console.WriteLine (n);
        }
2) The object allocated in the heap, when there is no reference to any variable, the object will be marked as garbage object, waiting for the garbage collector to recycle

The GC will regularly clean up garbage objects in the heap space. This time frequency is beyond the control of the programmer and is determined by the CLR. Therefore, when an object is marked as a garbage object, it is not necessarily recycled immediately.

3) Destructor

When recycling garbage objects, the destructor is automatically called by the GC. Mainly to perform some clean-up work.

The destructor does not have access modifiers, you cannot have your parameters, use "~" to modify. As the following code example:

class Program
    {
        // When defining the value type n, the space occupied by n in the stack will be immediately recovered by the CLR after the program exits the main function
        static void Main (string [] args)
        {
            int n = 5;

            OperateFile operate = new OperateFile ();

            operate.FileWrite ();
            // After executing the write operation, the destructor of this class will be called to release the control of the file object
            //Console.WriteLine(n);
        }
    }

    // Define the operation of the class on the file on the hard disk
    class OperateFile
    {
        // Define the method of writing files
        public void FileWrite ()
        {}

        // Define the action to be performed after calling this class
        ~ OperateFile ()
        {
// Release the control of the operation file object
        }
    }
Third, the difference between static members and instance members:

Static members need to be modified by the static keyword, while instance members are not modified by the static keyword. The difference between them is as follows:

class Program
    {
        static void Main (string [] args)
        {
            // The static member belongs to the class, and can be accessed directly by "class name. Static member"
            Person.Run ();

            // The instance member belongs to the object and needs to be accessed by "object name. Instance member"
            Person p = new Person ();
            p.Sing ();
        }
    }

    class Person
    {
        // Static member variable
        private static int nAge;
        // Instance member variables
        private string strName;

        public static void Run ()
        {
            Console.WriteLine ("I will run!");
        }

        public void Sing ()
        {
            Console.WriteLine ("I can sing");
        }
    }
When the class is loaded for the first time (that is, the class is first loaded into memory), all static members under the class will be loaded. As many objects as instance members have, as many objects will be created.

Static members are only loaded into the static storage area, only created once, and will not be released until the program exits.

Look at the code below:

class Program
    {
        static void Main (string [] args)
        {

            Person p = new Person ();
            Person p1 = new Person ();
            Person p2 = new Person ();

        }
    }

    class Person
    {
        // Static member variable
        private static int nAge;
        // Instance member variables
        private string strName;

        public static void Run ()
        {
            Console.WriteLine ("I will run!");
        }

        public void Sing ()
        {
            Console.WriteLine ("I can sing");
        }
    }
So what happened in memory? As shown below:



It is obvious from the above that defining static members can affect the execution efficiency of the program. So when do you define static member variables?

①When the variable needs to be shared ②When the method needs to be called repeatedly

2) Instance members cannot be called directly in static methods.

When the class is first loaded, the static members have been loaded into the static storage area. At this time, the class object may not be created, so the class member field cannot be called in the static method. The example code is as follows:



Neither this nor base keywords can be used in static methods.

②The object of the class can be created to indicate that the members of the object operate in static methods. The code is as follows:

 public static void Run ()
        {
            Person p = new Person ();
            p.strName = "Hadron";
            Console.WriteLine ("I will run!");
        }
③ Static methods can definitely be called in instance members, because static members must exist at this time, the code is as follows:

 public static void Run ()
        {
            Person p = new Person ();
            p.strName = "Hadron";
            Console.WriteLine ("I will run!");
        }

        public void Sing ()
        {
            // When the instance method is called, the object instance will be created, so you can access the instance field in the instance method
            this.strName = "Zi Qiang";
            strName = "子 强";

            // Call static member
            Run ();
            Console.WriteLine ("I can sing");
        }
Comparison of static members and instance members:

①The life cycle is different

Static members are only released when the program ends, and instance members are released when there is no object reference

② The storage location in the memory is different

Static members are stored in the static storage area, and instance members are in the managed heap.

Four, static class

① The static class is modified by the static keyword

 // Define two static classes
    static class Person
    {}

    internal static class Cat
    {}
② Only static member variables can be lived in static class, otherwise an error will be reported (because when accessing the instance member, the class object may not have been created yet)



③ There can be no instance constructor in the static class (if there is an instance constructor, the static class can be instantiated, all are static members, and no instance members are called)



The correct method of declaration:

    static class Person
    {
        // private int nAge;
        private static string strName;

        static Person ()
        {
        }
    }
④ The static class cannot be inherited. Decompile the two classes just now. The result is as follows:



You will find that the essence of a static class is an abstract sealed class, so it cannot be inherited and instantiated. Therefore, the constructor of the static class must not have an access modifier

2) So when do you declare static classes?

If all members of this class need to be shared, you can declare this class as a static class.

And you cannot declare a static type variable in a general object (when accessing the static variable, the object may not have been created yet).



3) Constructor of static class

Static classes can have static constructors (and all classes can have static constructors), as follows:

class Program
    {
        static void Main (string [] args)
        {
            Cat c;
            Cat c1 = new Cat ();

            Console.ReadKey ();
        }
    }

    class Cat
    {
        private int n;
        public string strName;

        // Instance constructor
        public Cat ()
        {
            Console.WriteLine ("Look who performs 2 first");
        }

        // Static constructor
        static Cat ()
        {
            Console.WriteLine ("Look who performs 1 first");
        }

    }
The results are as follows:



From this we can know that the static constructor will be executed before the instance constructor

And

            // Do not execute static constructor
            Cat c;
When we add the following code in the Main () function is:

static void Main (string [] args)
        {
            // Do not execute static constructor
            Cat c;
            Cat c1 = new Cat ();
            Cat c2 = new Cat ();

            Console.ReadKey ();
        }
The results are as follows:



Explain that the static constructor is executed only once.

Okay, this time the sharing is over. I hope to help you understand the basic concepts of C #.

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.