In-depth analysis of C # inheritance mechanism 2

xiaoxiao2021-03-06  55

Second, inheritance in C # meets the following rules: 1, inheritance is deliverable. If c is derived from B, B is derived from A, but c not only inherits the members of the declaration in B, but also inherits the members in A. The Object class is a base class for all classes.

2, derived class should be an extension of the base class. Detective classes can add new members, but they cannot remove the definitions of those already inherited.

3, the constructor and the destructor cannot be inherited. In addition to other members, they can be inherited whether they define what kind of access to them. The access method of members in the base class can only decide whether the derived class can access them.

4. If the derived class defines a new member of the same name as the successor, you can override the successful member. But this is not because of these members, just unable to access these members.

5, class can define virtual methods, virtual properties, and virtual index pools, which can overload these members, so that the class can display polymorphism.

6, derived classes can only be inherited from a class, and multiple inherits can be achieved by picking up.

The following code is an example of a subclass inherit the parent class:

Using System; Public Class ParentClass {PUBLIC PARENTCLASS () {Console.writeline ("Parent Class Constructor.");} public void print () {console.writeLine ("I'm a packet class.");}} public Class ChildClass: ParentClass () {Console.writeline ("Subclass constructor.");} public static void main () {childclass child = new childclass (); child.print ();}}

Program run output: parent class constructor. Subclass constructor. I'm a pent class. One of the above class named ParentClass, the class named ChildClass in the main function. What to do is to create a subclass of the existing code using the parent class ClassClass. 1. First, you must explain that ParentClass is the base class of ChildClass. This is done by making the following description in the ChildClass class: "public class childclass: parentclass". Behind the derived class identifier, with a semicolon ":" to indicate that the latter identifier is the base class. C # only supports single inheritance. Therefore, you can only specify a base class. 2. The function ofchildclass is almost equivalent to ParentClass. Therefore, it is also possible to say that ChildClass "is" ParentClass. In the case () method of ChildClass, the result of calling the print () method is verified. This subclass does not have its own print () method, which uses the Print () method in the ParentClass. The third line in the output result can be verified. 3. The base class is automatically initialized before the derived class initialization. The constructor of the ParentClass class is executed before the constructor of ChildClass.

转载请注明原文地址:https://www.9cbs.com/read-83908.html

New Post(0)