C# 中的基类和派生类是什么?
csharpprogrammingserver side programming更新于 2025/9/20 11:07:17
一个类可以从多个类或接口派生,这意味着它可以从多个基类或接口继承数据和函数。
例如,Vehicle 基类具有以下派生类。
Truck Bus Motobike
派生类继承了基类的成员变量和成员方法。
同样,Shape 类的派生类可以是 Rectangle,如下例所示。
示例
using System;
namespace Program {
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 Demo {
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

