C# 中的基类是什么?
csharpprogrammingserver side programming更新于 2025/10/14 3:07:17
创建类时,程序员不必编写全新的数据成员和成员函数,而是可以指定新类继承现有类的成员。这个现有类称为基类,新类称为派生类。
一个类可以从多个类或接口派生,这意味着它可以从多个基类或接口继承数据和函数。
以下是 C# 中基类的语法 −
<access-specifier> class <base_class> {
...
}
class <derived_class> : <base_class> {
...
}
我们来看一个例子 −
示例
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();
}
}
}

