继承 ( : )
继承允许在一个类中去使用另一个类中的数据,以达到代码复用
c#中叫做基类和派生类(等效于我们在其他语言中的父类和子类)
一个派生类拥有该基类的所有成员变量和成员方法
c#的继承是单继承(c++允许多继承)
不允许循环继承(相互继承)
简单的小例子看一下什么是继承
我们先定义一个形状类:
namespace Day04
{
internal class Shape
{
public int width;
public int height;
public void setWidth(int width)
{
this.width = width;
}
public void setHeight(int height)
{
this.height = height;
}
}
}
定义一个矩形类并让它继承自形状类:
namespace Day04
{
internal class Rectangle : Shape
{
public int getArea()
{
return width * height;
}
}
}
定义一个三角形类也继承自形状类:
namespace Day04
{
internal class Triangle : Shape
{
public int getArea()
{
return (height * width / 2);
}
}
}
测试类:
using Day04;
internal class Program
{
private static void Main(string[] args)
{
Rectangle rec = new Rectangle();
rec.setHeight(5);
rec.setWidth(10);
Console.WriteLine(rec.getArea());
Triangle tri