C#继承的简单应用

比如,现在有一些图形,需要计算他们的面积,计算面积的方法都不一样,可以这么做

声明一个抽象类

1 //基类 2 abstract class Shape3  {4 //抽象方法 计算面积5 public abstract double ComputerArea();6 7 }

声明子类

//子类 继承Shape 实现抽象方法 class Circle : Shape { private double _radius; //构造函数 public Circle(double radius) => _radius = radius; //实现抽象方法 public override double ComputerArea() { return _radius * _radius * Math.PI; } } //子类 继承Shape 实现抽象方法 class Rectangle : Shape { private double _width; private double _height; //构造函数 public Rectangle(double width, double height) { _width = width; _height = height; } //实现抽象方法 public override double ComputerArea() { return _width * _height; } } //子类 继承Shape 实现抽象方法 class Triangle : Shape { private double _bottom; private double _height; //构造函数 public Triangle(double bottom, double height) { _bottom = bottom; _height = height; } //实现抽象方法 public override double ComputerArea() { return _bottom * _height / 2; } }

声明计算类

 1 //计算类 2 class Calculate 3  { 4 //传入一个父类作为参数,调用方法 5 public void Calc(Shape shape) 6  { 7  8 Console.WriteLine($"{shape.GetType().Name}的面积:{shape.ComputerArea()}"); 9  }10 }

 

测试

class Program { static void Main(string[] args) { var circle = new Circle(5); var rect = new Rectangle(5, 10); var triangle = new Triangle(6, 8); var calc = new Calculate(); calc.Calc(circle); calc.Calc(rect); calc.Calc(triangle); } }

运行结果

 

技术图片

实际上 如果是只有这个方法要实现的话,继承接口也是可以的!

 

相关文章