C#中的继承是面向对象编程的核心特性之一,它允许你创建一个新类(子类或者派生类),来继承现有类(基类或者父类)的成员。继承在C#当中不仅仅简化了代码的重新使用,还帮助我们实现了多态,使得同一操作可以作用于不同类型的对象
继承是指一个类(子类)从另一个类(基类)获得属性和方法的能力,基类包含通用的属性和方法,子类可以继承这些成员并根据需要进行扩展或者修改。
C#使用冒号(:)符号来标识继承关系
- using System;
-
- namespace 继承
- {
- public class Pet
- {
- public string Name;
- }
-
- public class Dog : Pet
- {
- public Dog()
- {
- this.Name = "123"; // 直接设置当前实例的 Name 属性
- Console.WriteLine(this.Name); // 打印当前实例的 Name 属性
- }
- }
-
- internal class Program
- {
- static void Main(string[] args)
- {
- Dog myDog = new Dog(); // 正确调用 Dog 类的构造函数
- // Console.WriteLine(myDog.Name); // 如果需要,也可以这样打印 myDog 的 Name 属性
- }
- }
- }
- using System;
-
-
- namespace 继承
- {
- public class Animal
- {
- public Animal()
- {
- Console.WriteLine("先执行");
- }
- }
-
- public class Dog : Animal
- {
- public Dog() : base()
- //base 关键字用于访问基类(父类)的成员,包括属性、方法和构造函数
- {
- Console.WriteLine("后执行");
- }
- }
-
- internal class Program
- {
- static void Main(string[] args)
- {
- Dog dog = new Dog();
- dog.ToString();
- }
- }
- }
- //当创建 Dog 类的实例时,以下是构造函数调用的顺序:
- //Dog 类的构造函数被调用。
- //由于 Dog 类的构造函数中使用了 base(),所以 Animal 类的构造函数首先被调用输出
- //然后控制权返回到 Dog 类的构造函数,输出
- using System;
-
-
- namespace 继承
- {
- public class Animal
- {
- public virtual void Dog()
- {
- Console.WriteLine("准备复写");
- }
- }
-
- public class D : Animal
- {
- public override void Dog()
- {
- Console.WriteLine("复写成功");
- }
- }
-
- internal class Program
- {
- static void Main(string[] args)
- {
- D dog = new D();
- dog.Dog();
- }
- }
- }
object类是所有类的基础共类,它是唯一的非派生类,是继承层次结构的基础,对于其他类来说,父类和子类的概念都是相对的
继承涉及访问修饰符的使用: