如何在 C# 中继承一个类?
csharpprogrammingserver side programming更新于 2025/5/24 17:37:17
继承允许我们根据另一个类来定义一个类,这使得应用程序的创建和维护更加容易。
创建类时,程序员不必编写全新的数据成员和成员函数,而是可以指定新类继承现有类的成员。这个现有类称为基类,新类称为派生类。一个类可以从多个类或接口派生,这意味着它可以从多个基类或接口继承数据和函数。
让我们看一个例子 −
示例
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 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

