What is a constructor? What is a reference type?

Source: Internet
Author: User
A reference type constructor is a special method that initializes an instance of a type to a good state. When you create an instance of a reference type, you first allocate memory for the data fields of the instance, then initialize the additional fields of the object (type object pointer and synchronized block index), and finally The type's instance constructor is called to set the object's initialization state.

When constructing a reference type object, the memory allocated for the object is always returned to 0 before the instance constructor of the electrophoretic type. All fields that are not rewritten by the constructor are guaranteed to obtain 0 or null values. Unlike other methods, the strength constructor can never be inherited, that is, the class only has a smooth constructor that is defined by the class itself.

Since instance constructors can never be inherited, instance constructors cannot use the following modifiers: Virtual, new, override, sealed, and abstract.

If the class does not explicitly define any constructors, the C # compiler will default to a default parameterless constructor. In her implementation, it simply calls the parameterless constructor of the base class. If the class modifier is abstract, the accessibility of the default constructor generated by the compiler is product; otherwise, the constructor will be assigned a publicly accessible property. If the base class does not provide a no-argument constructor, the derived class must explicitly call a base class constructor, otherwise the compiler will report an error. If the class modifier is static (sealed and abstract), the compiler will not generate a default constructor in the class definition at all.

A type can define multiple instance constructors. Each constructor must have a different signature, and each can have a different accessible property. In order to make the code "verifiable", the class's strength constructor must call the base class's constructor before accessing any fields inherited from the base class. If the constructor of the derived class does not explicitly call a base class constructor, the C # compiler automatically generates a call to the default base class constructor. Eventually, the public no-argument constructor of System.Object is called. This constructor does nothing and returns directly. Since System.Object has no instance data fields, its constructor has nothing to do. In rare cases, type instances can be created without invoking the instance constructor. A typical example is the MemberwiseClone method of Object. The role of this method is to allocate memory, initialize additional fields of the object, and then copy the source object's own data to the new object. In addition, when deserializing an object with a runtime seriallizer, the constructor does not need to be called on the same trip.

The deserialization uses the System.Runtime.Serialization.FormatterServices type GetUninitalizedObject or GetSafeUninitailizedObject method to allocate memory for the object. A constructor is not called during this time.
 Tip: Don't call virtual methods in the constructor anymore.
The reason is that if the instantiated type overrides the virtual method, the implementation of the virtual method of the derived type will be performed, but at this time, the initialization of all fields in the inheritance hierarchy (the constructor of the instantiated type) Not yet running). So calling virtual methods can lead to unpredictable behavior. After all, this is because when a virtual method is called, the actual type of the method is not selected until runtime. Value type (struct) constructors Value type (struct) constructors work very differently from reference type (class) constructors. The CLR always allows the creation of instances of value types, and there is no way to prevent the instantiation of value types. So, value types don't actually need to define a constructor, and the C # compiler doesn't inline a default parameterless constructor for value types at all. Consider the following code: internal struct Point {public int m_x, m_y;} internal sealed class Reactangel {public Point m_TopLeft, m_bottomRight;} To construct a Rectangle, you must use the new operator, and you must specify a constructor. In this example, the default constructor automatically generated by the C # compiler is called. Allocates memory for Reatangle, which contains two instances of the Point value type. For performance reasons, the CLR does not actively call a constructor for every value type field contained in a reference type, but, as mentioned earlier, value type fields are initialized to 0 or null. The CLR does allow a constructor to be defined for a value type, but it must be explicitly called to execute. internal struct Point {public int m_x, m_y; public Point (int x, int y) {m_x = x; m_y = y;)) internal sealed class Reactangel {public Point m_TopLeft, m_bottomRight; public Reactangel () {this.m_TopLeft = new Point (1,2); this.m_bottomRight = new Point (100,200);}} An instance constructor of a value type will only execute if it is explicitly called. Therefore, if the constructor of Rectangle does not use the new operator to call the constructor of Point, thereby initializing the m_TopLeft and m_bottomRight fields of Reatangle, then the m_x and m_y fields in both point fields will be 0. Rewrite the above code: internal struct Point {public int m_x, m_y; public Point () {m_x = 5; m_y = 6;}} internal sealed class Reactangel {public Point m_TopLeft, m_bottomRight; public Reactangel () {}} Now when constructing a new Rectangle class How many m_x and m_y fields in the two Point fields will be initialized, 0 or 5? You may think that the C # compiler will generate code in Reactangel's constructor, and automatically call Point's default parameterless constructor for the two fields of Reactangel. However, to enhance the runtime performance of the application, the C # compiler does not automatically generate such code. In fact, even if a value type provides a parameterless constructor, many compilers never generate code to call it. In order to execute a value type parameterless constructor, the developer must add code that explicitly calls the value type constructor. But will the two fields of Point ’be initialized to 0 for this reason?
The result: The C # compiler deliberately does not allow value types to define non-argument constructors, in order to prevent developers from being confused when such constructors are called. Since no parameterless constructor can be defined, the compiler will never generate code that automatically calls it. Without a parameterless constructor, a value type field is always initialized to 0 or null.
Type constructor: Also called a static constructor, a class constructor, or a type initializer. Type constructors can be applied with reference types and value types. The role of an instance constructor is to set the initial state of an instance of a type. Correspondingly, the role of the type constructor is to set the initial state of the type. Types do not have a type constructor defined by default, and if defined, there can only be one. In addition, type constructors never have parameters. internal sealed class SomeRefType {static SomeRefType () {// the first time you execute the code here}} internal struct SomeValType {static SomeValType () {// the first time you execute the code here}} It can be seen that the type construction A constructor is similar to defining a parameterless instance constructor, except that it must be marked as static. In addition, type constructors are always private. The reason it is private is to prevent any developer from writing code to call it, and the CLR is always responsible for his calls. Tip: Although you can define a type constructor in a value type, never really do that, because the CLR sometimes doesn't call a value type's static constructor:
For example internal struct SomeValType {static SomeValType () {Console.WriteLine ("This sentence will never be displayed");} public int m_x;} class Program {static void Main (string [] args) {SomeValType [] a = new SomeValType [10]; a [0] .m_x = 123; Console.WriteLine (a [0] .m_x); Console.ReadKey ();}} The code of the type constructor can only access the static fields of the type, and his An unusual use is to initialize these fields.
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.