比如,现在有一些图形,需要计算他们的面积,计算面积的方法都不一样,可以这么做
声明一个抽象类
//基类
abstract class Shape
{
//抽象方法 计算面积
public abstract double ComputerArea();
}
声明子类
//子类 继承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;
}
}
声明计算类
//计算类
class Calculate
{
//传入一个父类作为参数,调用方法
public void Calc(Shape shape)
{
Console.WriteLine($"{shape.GetType().Name}的面积:{shape.ComputerArea()}");
}
}
测试
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);
}
}
运行结果
实际上 如果是只有这个方法要实现的话,继承接口也是可以的!
实例扩展:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace inheritApplication
{
//程序员类(基类)
class Programmer
{
public string name = "我是程序员";
}
//java程序员类
class Jpro
{
public string name = "java程序员";
public string language = "我用java语法写代码";
}
//C程序员类
class Cpro
{
public string name = "C#程序员";
public string language = "我用C#语法写代码";
}
//编写项目类
class Pro : Programmer //继承基类
{
public void WriteProgram(Jpro program) //继承java程序员类
{
Console.WriteLine("" + program.name + ":" + name + "," + program.language + "");
}
public void WriteProgram(Cpro program)
{
Console.WriteLine("" + program.name + ":" + name + "," + program.language + "");
}
}
//主程序
class Program
{
static void Main(string[] args)
{
Pro p = new Pro();
Jpro p1 = new Jpro();
p.WriteProgram(p1);
Cpro p2 = new Cpro();
p.WriteProgram(p2);
Console.ReadKey();
}
}
}
到此这篇关于关于C#继承的简单应用代码分析的文章就介绍到这了,更多相关C#继承的简单应用内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!