什么是C#中的继承?
通过继承,您可以用另一个类来定义一个类,这使创建和维护应用程序变得更加容易。这也提供了重用代码功能并加快实现时间的机会。
继承基于基类以及派生类的概念。一个类可以从一个以上的类或接口派生,这意味着它可以从多个基类或接口继承数据和函数。
让我们看一个基类和派生类的例子。在这里,Shape是基类,而Rectangle是派生类-
class Rectangle: Shape {
//方法
}以下是显示如何在继承中使用基类和派生类的示例:
示例
using System;
namespace InheritanceApplication {
class Shape {
public void setWidth(int w) {
width = w;
}
public void setHeight(int h) {
height = h;
}
protected int width;
protected int height;
}
//派生类
class Rectangle: Shape {
public int getArea() {
return (width * height);
}
}
class RectangleTester {
static void Main(string[] args) {
Rectangle Rect = new Rectangle();
Rect.setWidth(5);
Rect.setHeight(7);
//打印对象的区域。
Console.WriteLine("Total area: {0}", Rect.getArea());
Console.ReadKey();
}
}
}输出结果
Total area: 35