共用方式為


How New and Finalize Methods Work in a Class Hierarchy 

Whenever an instance of a class is created, the common language runtime (CLR) attempts to execute a procedure named New, if it exists in that object. New is a type of procedure called a constructor that is used to initialize new objects before any other code in an object executes. A New constructor can be used to open files, connect to databases, initialize variables, and take care of any other tasks that need to be done before an object can be used.

When an instance of a derived class is created, the Sub New constructor of the base class executes first, followed by constructors in derived classes. This happens because the first line of code in a Sub New constructor uses the syntax MyBase.New()to call the constructor of the class immediately above itself in the class hierarchy. The Sub New constructor is then called for each class in the class hierarchy until the constructor for the base class is reached. At that point, the code in the constructor for the base class executes, followed by the code in each constructor in all derived classes and the code in the most derived classes is executed last.

Constructors and Inheritance

When an object is no longer needed, the CLR calls the Finalize method for that object before freeing its memory. The Finalize method is called a destructor because it performs cleanup tasks, such as saving state information, closing files and connections to databases, and other tasks that must be done before releasing the object.

Constructors Inheritance2

See Also

Concepts

Object Lifetime: How Objects Are Created and Destroyed