Tutorial - C# learning

6. Succession

In C# language, all classes are inherited from the Object class. The properties and methods in the Object class can be used in any class.

It is very easy to implement inheritance in C# language. You only need to use: symbol to complete the representation of inheritance between classes.

Access modifier   class  ClassA:ClassB
{
    //Class member
}

Of which:

  • Access modifiers: including public and internal.
  • ClassA: it is called subclass and derived class. Members in ClassB can be directly used in subclasses.
  • ClassB: called parent class and base class.

Characteristics of inheritance:

  • A derived class is an extension of a base class. A derived class can add new members, but cannot remove the definition of an inherited member.
  • Inheritance is transitive. If C derives from B and B derives from a, C inherits not only the member declared in B, but also the member declared in a. A class can only have one parent, but a parent can have multiple subclasses.
  • Constructors and destructors cannot be inherited. Other members can be inherited. The way members in the base class are accessed can only determine whether derived classes can access them.
  • If the defined members have the same name, they can only inherit from the new members, but they cannot be deleted.
  • Class can define virtual methods, virtual attributes and virtual index indicators. Its derived classes can overload these members, so that the class can show polymorphism.
  • Derived classes can only inherit from one class, and multiple inheritance can be realized through interfaces.

6.1 Object class

Object class is the most primitive and important class in C# language. Each class is its subclass. It implements the basic methods that each class must have.

Four common methods are provided in the Object class, namely Equals, GetHashCode, GetType and ToString methods.

6.1.1 Equals method: judge whether two objects are equal

using System;
class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
};
class Program
{
    static void Main(string[] args)
    {
        Student stu1 = new Student();
        Student stu2 = new Student();
        bool flag = Equals(stu1, stu2);
        Console.WriteLine("stu1 and stu2 The comparison results are:{0}", flag);

        Student stu3 = stu1;
        Console.WriteLine("stu1 and stu3 The comparison results are:{0}", stu1.Equals(stu3));
    }
}
// The comparison result of stu1 and stu2 is False
// The result of stu1 and stu3 comparison is: True

6.1.2 GetHashCode method: get hash code

using System;
class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
};
class Program
{
    static void Main(string[] args)
    {
        Student stu1 = new Student();
        Student stu2 = new Student();
        Console.WriteLine("stu1 The hash code of is:" + stu1.GetHashCode());
        Console.WriteLine("stu2 The hash code of is:" + stu2.GetHashCode());
    }
}
// The hash code of stu1 is 58225482
// The hash code of stu2 is 54267293

Different instances have different hash values, so you can also use this method to compare whether objects are equal.

6.1.3 GetType method: get object type

using System;
class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
};
class Program
{
    static void Main(string[] args)
    {
        int i = 100;
        string str = "abc";
        Student stu = new Student();
        Console.WriteLine(i.GetType());
        Console.WriteLine(str.GetType());
        Console.WriteLine(stu.GetType());
    }
}
// System.Int32
// System.String
// Student

6.1.4 ToString method: returns the string of the object instance

using System;
class Program
{
    static void Main(string[] args)
    {
        Int32 a = 123456;
        Object b = new Object();
        Console.WriteLine("Value type(Int32 type)The representation of the string:{0}", a.ToString());
        Console.WriteLine("The representation of the reference type string:{0}", b.ToString());
    }
}
// Expression of string of value type (Int32 type): 123456
// Expression of reference type string: system Object

6.2 base keyword

The method with the same name defined in the subclass is equivalent to redefining a method in the subclass. The object in the subclass cannot call the method with the same name in the parent class, but the method in the subclass is called. Therefore, it is often said to hide the method with the same name in the parent class.

In the inheritance relationship, if the subclass needs to call the members in the parent class, it can be completed with the help of the base keyword. The specific usage is as follows.

base. Parent class member

Note: users will encounter this and base keywords in the program. This keyword represents the object of the current class, while base keyword represents the object in the parent class.

6.3 virtual keyword

In C# language, by default, the members in the class are non virtual. Usually, the members in the class are defined as virtual, indicating that these members will overwrite the contents after inheritance.

//Modification method
 Access modifier   virtual  Return value type method name
{
    Statement block;
}

The virtual keyword cannot modify a member decorated with static. (why?)

using System;
class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Sex { get; set; }

    public virtual void Print()
    {
        Console.WriteLine("No.:" + Id);
        Console.WriteLine("full name:" + Name);
        Console.WriteLine("Gender:" + Sex);
    }
}
class Student : Person
{
    public string Major { get; set; }
    public string Grade { get; set; }
    public override void Print()
    {
        base.Print();
        Console.WriteLine("Major:" + Major);
        Console.WriteLine("Grade:" + Grade);
    }
}
class Program
{
    static void Main(string[] args)
    {
        Student stu = new Student();
        stu.Id = 1;
        stu.Name = "Kint";
        stu.Sex = "Male";
        stu.Major = "Software";
        stu.Grade = "undergraduate";
        stu.Print();
    }
}
// No.: 1
// Name: Kint
// Gender: Male
// Major: Software
// Grade: undergradate

Add the overridden ToString method in the Student class. The code is as follows.

using System;
class Student
{
    public string Major { get; set; }
    public string Grade { get; set; }
    public override string ToString()
    {
        return "Major:" + Major + "\n Grade:" + Grade;
    }
}
class Program
{
    static void Main(string[] args)
    {
        Student stu = new Student();
        stu.Major = "Software";
        stu.Grade = "undergraduate";
        Console.WriteLine(stu.ToString());
    }
}
// Major: Software
// Grade: undergradate

In addition to ToString method, Equals method and GetHashCode method can also be overridden in class.

6.4 abstract keyword

Abstract keyword is used to declare abstract classes or abstract methods.

The syntax for defining abstract classes is as follows. There can be non abstract methods in instantiated classes, but there can be no abstract methods in non instantiated classes.

Access modifier   abstract class  Class name
{
    //Class member
}

Abstract method is a method without method body, which only contains the definition of method. The syntax form is as follows. Abstract methods must be defined in abstract classes.

Access modifier   abstract  Method return value type method name(parameter list);

Abstract methods and non abstract methods can be defined in abstract classes. Usually, abstract classes will be inherited by other classes and override the abstract methods or virtual methods in them.

using System;
abstract class ExamResult
{
    //Student number
    public int Id { get; set; }
    //Mathematics achievement
    public double Math { get; set; }
    //English achievement
    public double English { get; set; }
    //Calculate the total score
    public abstract void Total();
}
class MathMajor : ExamResult
{
    public override void Total()
    {
        double total = Math * 0.6 + English * 0.4;
        Console.WriteLine("Student number is" + Id + "The scores of students majoring in mathematics are:" + total);
    }
}
class EnglishMajor : ExamResult
{
    public override void Total()
    {
        double total = Math * 0.4 + English * 0.6;
        Console.WriteLine("Student number is" + Id + "The scores of English majors are:" + total);
    }
}
class Program
{
    static void Main(string[] args)
    {
        MathMajor mathMajor = new MathMajor();
        mathMajor.Id = 1;
        mathMajor.English = 80;
        mathMajor.Math = 90;
        mathMajor.Total();
        EnglishMajor englishMajor = new EnglishMajor();
        englishMajor.Id = 2;
        englishMajor.English = 80;
        englishMajor.Math = 90;
        englishMajor.Total();
    }
}
// The grade of students majoring in mathematics with student number 1 is 86
// The grade of English majors with student number 2 is 84

6.5 sealed keyword

The sealed keyword is used to declare a sealed class or sealed method. Sealed classes cannot be inherited and sealed methods cannot be overridden.

The sealed method must appear in the subclass and be the parent method overridden by the subclass, that is, the sealed keyword must be used together with the override keyword.

In practical application, in the released software products, some classes or methods do not want to be inherited or rewritten. They can be defined as sealed classes or sealed methods.

abstract class AreaAbstract
{
    public abstract void Area();
}
class Rectangle : AreaAbstract
{
    public double Width { get; set; }
    public double Length { get; set; }
    public sealed override void Area()
    {
        Console.WriteLine("The area of the rectangle is:" + Width * Length);
    }
}
sealed class Circle : AreaAbstract
{
    public double r { get; set; }
    public override void Area()
    {
        Console.WriteLine("The area of the circle is:" + r * 3.14 * 3.14);
    }
}

In the above example, the Circle class cannot be inherited; The Area method in the Rectangle class cannot be overridden.

6.6 modifier summary

Modifier be applied toexplain
newFunction memberMembers hide inherited members with the same signature
staticAll membersMembers do not act on specific instances of a class, also known as class members, not instance members
virtualFunction members onlyMembers can be overridden by derived classes
abstractFunction members onlyThe virtual member defines the signature of the member, but does not provide implementation code
overrideFunction members onlyMember overrides an inherited virtual or abstract member
sealedClasses, methods, and propertiesClass cannot inherit from sealed class; For properties and methods, members override inherited virtual members, but no member in any derived class can override that member. This modifier must be used with override

6.7 relationship between constructors

using System;
class A
{
    public A()
    {
        Console.WriteLine("A Class constructor");
    }
}
class B : A
{
    public B()
    {
        Console.WriteLine("B Class constructor");
    }
    public B(string name)
    {
        Console.WriteLine("B Constructor with parameters in class. The value passed in is:" + name);
    }
}
class Program
{
    static void Main(string[] args)
    {
        B b = new B();
        Console.WriteLine("***************");
        B bb = new B("Kint");
    }
}
// Class A constructor
// Class B constructor
// ***************
// Class A constructor
// Class B constructor with parameters. The value passed in is: kind

By default, the parameterless constructor of the parent class will be automatically called in the constructor of the subclass. If you need to call the constructor with parameters in the parent class, use the form of: base (parameter).

using System;
class A
{
    public A()
    {
        Console.WriteLine("A Class constructor");
    }
    public A(string name)
    {
        Console.WriteLine("A Class. The passed in value is:" + name);
    }
}
class B : A
{
    public B()
    {
        Console.WriteLine("B Class constructor");
    }
    public B(string name) : base(name)    //Call the constructor with parameters in the parent class
    {
        Console.WriteLine("B Constructor with parameters in class. The value passed in is:" + name);
    }
}
class Program
{
    static void Main(string[] args)
    {
        B b = new B();
        Console.WriteLine("***************");
        B bb = new B("Kint");
    }
}
// Class A constructor
// Class B constructor
// ***************
// Class A constructor. The value passed in is: kind
// Class B constructor with parameters. The value passed in is: kind

Note: if there is no parameterless constructor in the parent class, the constructor of the parent class must be inherited in the constructor of the child class, otherwise the program cannot be compiled successfully.

6.8 polymorphism

In C# language, polymorphism is called runtime polymorphism, that is, when the program runs, it automatically makes the instance of the parent class call the method rewritten in the subclass. It is not completed in the program compilation stage.

Using inheritance to implement polymorphism must meet the following two conditions.

  • Subclasses must have overridden methods of the parent class when inheriting from the parent class.
  • When calling the overridden method, the object of the parent class must be created to point to the child class (that is, the child class is converted to the parent class).
using System;
abstract class Major
{
    public int Id { get; set; }
    public string Name { get; set; }
    public abstract void Requirement();
}
class Undergraduate : Major
{
    public override void Requirement()
    {
        Console.WriteLine("Undergraduate has a four-year academic system and must complete 48 credits");
    }
}
class Graduate : Major
{
    public override void Requirement()
    {
        Console.WriteLine("The postgraduate education system is 3 years, and 32 credits must be completed");
    }
}
class Program
{
    static void Main(string[] args)
    {
        Major major1 = new Undergraduate();
        major1.Id = 1;
        major1.Name = "Zhang San";
        Console.WriteLine("Undergraduate information:");
        Console.WriteLine("Student number:" + major1.Id + "full name:" + major1.Name);
        major1.Requirement();
        Major major2 = new Graduate();
        major2.Id = 2;
        major2.Name = "Li Si";
        Console.WriteLine("Graduate information:");
        Console.WriteLine("Student number:" + major2.Id + "full name:" + major2.Name);
        major2.Requirement();
    }
}
// Undergraduate information:
// Student No.: 1 Name: Zhang San
// Undergraduate has a four-year academic system and must complete 48 credits
// Graduate information:
// Student No.: 2 Name: Li Si
// The postgraduate education system is 3 years, and 32 credits must be completed

Thinking 1: why can't the virtual keyword modify members decorated with static?

Static method is a static method, and the compiler will keep the implementation of this method at compile time. In other words, this method belongs to a class, but does not belong to any member. This method will exist regardless of whether the instance of this class exists or not.

The virtual method is a virtual method that does not exist in the real memory space until the instantiated object is called.

A static method is real, while a virtual method can be overridden by a derived class. The two conflict.

Keywords: C# microsoft

Added by OM2 on Sat, 05 Mar 2022 11:16:59 +0200