AI智能
改变未来

C#抽象类与接口

  总结一下在C#语言中关于抽象类与接口的相关知识,来源B站刘铁猛老师的C#课程:《C#语言入门详解》。

1.抽象类是未完全实现逻辑的类

class Program{static void Main(string[] args){Car car = new Car();//实例化Car的对象carRaceCar raceCar = new RaceCar();//实例化car.run();raceCar.run();Console.ReadLine();}}abstract class Vehicle//因为类中包含未实现逻辑的run()方法,所以Vehicle为一个抽象类,使用abstract关键字修饰{public void Stop(){System.Console.WriteLine(\"Stopped...\");}public void Fill(){System.Console.WriteLine(\"Pay and fill...\");}public abstract void run();//抽象类是未完全实现逻辑的类,此处的run()方法就是未完全实现逻辑的类成员}class Car : Vehicle{public override void run()//override修饰符,重写基类的run()方法,实现在基类中未实现的逻辑{System.Console.WriteLine(\"car is running\");}}class RaceCar : Vehicle{public override void run(){System.Console.WriteLine(\"race car is running\");}}

  在基类Vehicle中,只有run()方法没有实现逻辑(没有代码体),所以Vehicle是未完全实现逻辑的类,即为抽象类。
执行结果:

2.接口是完全未实现逻辑的“类”

class Program{static void Main(string[] args){Car car = new Car();//实例化Car的对象carRaceCar raceCar = new RaceCar();//实例化car.Run();raceCar.Run();Console.ReadLine();}}abstract class VehicleBase//VehicleBase为完全未实现逻辑的类{abstract public void Stop();abstract public void Fill();abstract public void Run();}abstract class Vehicle : VehicleBase//继承了抽象类VehicleBase,所以Vehicle也要是一个抽象类{public override void Stop(){System.Console.WriteLine(\"Stopped...\");}public override void Fill(){System.Console.WriteLine(\"Pay and fill...\");}//public abstract void Run();//基类中包含Run()方法,所以不用再写}class Car : Vehicle{public override void Run()//override修饰符,重写基类的run()方法,实现在基类中未实现的逻辑{System.Console.WriteLine(\"car is running\");}}class RaceCar : Vehicle{public override void Run(){System.Console.WriteLine(\"race car is running\");}}

此处构建了一个完全未实现逻辑的抽象类VehicleBase,然后由Vehicle类继承并实现VehicleBase类的逻辑,其中Run()方法并未实现,交由Vehicle的子类Car和RaceCar去实现。此段代码在C#中可用接口进行替换:

class Program{static void Main(string[] args){Car car = new Car();//实例化Car的对象carRaceCar raceCar = new RaceCar();//实例化car.Run();raceCar.Run();Console.ReadLine();}}interface IVehicle//IVehicle为接口,由interface关键字修饰{void Stop();//接口的属性和方法都应默认为public,且自带抽象属性,所以不用再用abstract和public关键字进行修饰void Fill();void Run();}abstract class Vehicle : IVehicle//因为Vehicle中并没有实现Run()方法的逻辑,所以Vehicle要是一个抽象类{public void Stop(){System.Console.WriteLine(\"Stopped...\");}public void Fill(){System.Console.WriteLine(\"Pay and fill...\");}public abstract void Run();//由Vehicle的子类来实现Run()的逻辑}class Car : Vehicle{public override void Run()//override修饰符,重写基类的run()方法,实现在基类中未实现的逻辑{System.Console.WriteLine(\"car is running\");}}class RaceCar : Vehicle{public override void Run(){System.Console.WriteLine(\"race car is running\");}}

使用接口对“完全未实现逻辑的类”进行替换,实现了一个小架构,也初步掌握和理解了接口的使用。

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » C#抽象类与接口