Inheritance is one of the most important concepts in object-oriented programming. Inheritance allows us to define a class based on one class to define another class. When a class is derived from another class, the derived class inherits the characteristics from the base class
The idea of inheritance is realized Belongs to (IS-A ) relation. For example, mammals are (IS-A) animals, dogs are (IS-A) mammals, so dogs are (IS-A) animals.
Base class and derived class:
In C#, a derived class inherits members, methods, properties, fields, events, index indicators from its direct base class but except for constructors and destructors function.
Write an example below.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Test { class Anlimal //定义一个基类 { protected int foot = 4; protected double weight = 22.4; protected void say(string type, string call) { Console.WriteLine("类别:{0},叫声:{1} ",type,call); } } //Dog 继承Anlimal class Dog:Anlimal { static void Main(string[] args) { Dog dog = new Dog(); int foot = dog.foot; double weight = dog.weight; Console.WriteLine("dog foot: {0}\ndog weight:{1}",foot,weight); dog.say("狗", "汪汪"); } } }
Result
Multiple inheritance:
C# does not support multiple inheritance. However, you can use interfaces to implement multiple inheritance. In the above example, we added a smallanlimal interface for it
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Test { class Anlimal //定义一个基类 { protected int foot = 4; protected double weight = 22.4; protected void say(string type, string call) { Console.WriteLine("类别:{0},叫声:{1} ",type,call); } } public interface smallanlimal //添加一个接口 接口只声明方法在子类中实现 { protected void hight(double hight); } //Dog 继承Anlimal class Dog:Anlimal,smallanlimal { public void hight(double hight) //实现接口 { Console.WriteLine("Hight: {0}",hight); } static void Main(string[] args) { Dog dog = new Dog(); int foot = dog.foot; double weight = dog.weight; dog.hight(23.23); Console.WriteLine("dog foot: {0}\ndog weight:{1}",foot,weight); dog.say("狗", "汪汪"); } } }
The above is the content of C# Learning Diary 22---Multiple Inheritance. For more related content, please pay attention to PHP Chinese Net (www.php.cn)!