abstract 修饰符指示被修改内容的实现已丢失或不完整。 abstract 修饰符可用于类、方法、属性、索引和事件。 在类声明中使用 abstrac 修饰符来指示某个类仅用作其他类的基类,而不用于自行进行实例化。 标记为抽象的成员必须由派生自抽象类的非抽象类来实现。
示例
在此示例中,类 Square 必须提供 GetArea 的实现,因为它派生自 Shape :
abstract class Shape
{
public abstract int GetArea();
}
class Square : Shape
{
int side;
public Square(int n) => side = n;
// GetArea method is required to avoid a compile-time error.
public override int GetArea() => side * side;
static void Main()
{
var sq = new Square(12);
Console.WriteLine($"Area of the square = {sq.GetArea()}");
}
}
// Output: Area of the square = 144
抽象类具有以下功能:
抽

本文探讨了抽象类在编程中的关键概念,包括其定义、为何存在、如何使用抽象方法和属性,以及派生类的实现规则。通过实例和Microsoft官方文档,讲解了抽象类与密封类的区别,并展示了如何在接口实现中运用抽象类。阅读本文,掌握抽象类在设计继承体系中的核心作用。
最低0.47元/天 解锁文章
2472

被折叠的 条评论
为什么被折叠?



