在本文中,我们展示了如何在C#中使用抽象类。
未完成类中的抽象类。它必须在其子类中实现。抽象类是用abstract
关键字创建的。我们可以创建抽象方法和成员字段。
抽象类的目的是为后代类提供通用定义。
不能实例化抽象类。如果一个类至少包含一个抽象方法,那么它也必须声明为抽象方法。不能实现抽象方法;他们只是声明方法的签名。当我们继承一个抽象类时,所有的抽象方法都必须由派生类实现。此外,必须以较少限制的可见性相同的方式声明这些方法。
与接口不同,抽象类可能有完全实现的方法,也可能有定义的成员字段。所以抽象类可以提供部分实现。我们将一些通用功能放入抽象类中。
C#抽象类示例
下面的例子创建了一个抽象类。
var c = new Circle(12, 45, 22); Console.WriteLine(c); Console.WriteLine($"Area of circle: {c.Area()}"); Console.WriteLine(c.GetCoordinates()); Console.WriteLine("---------------------"); var r = new Rectangle(10, 20, 50, 60); Console.WriteLine(r); Console.WriteLine($"Area of rectangle: {r.Area()}"); Console.WriteLine(r.GetCoordinates()); abstract class Drawing { protected int x = 0; protected int y = 0; public abstract double Area(); public string GetCoordinates() { return $"x: {x}, y: {y}"; } } class Circle : Drawing { private int r; public Circle(int x, int y, int r) { this.x = x; this.y = y; this.r = r; } public override double Area() { return this.r * this.r * Math.PI; } public override string ToString() { return $"Circle at x: {x}, y: {x}, radius: {r}"; } } class Rectangle : Drawing { private int width; private int height; public Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } public override double Area() { return this.width * this.height; } public override string ToString() { return $"Rectangle at x: {x}, y: {y}, w: {width} h: {height}"; } }
我们有一个抽象基Drawing
类。该类定义了两个成员字段,定义了一个方法并声明了一个方法。其中一种方法是抽象的,另一种是完全实现的。Drawing
类是抽象的,因为我们无法绘制它。我们可以画一个圆、一个点或一个正方形。Drawing
类具有我们可以绘制的对象的一些通用功能。
abstract class Drawing
我们使用abstract
关键字来定义一个抽象类。
public abstract double Area();
抽象方法也以abstract
关键字开头。
class Circle : Drawing
Circle是Drawing
类的子类。它必须实现抽象的Area
方法。
private int r;
我们声明了radius成员字段,它特定于Circle
类。
public Circle(int x, int y, int r) { this.x = x; this.y = y; this.r = r; }
这是Circle
的构造函数;它设置成员变量。x
和y
变量继承自Drawing
。
public override double Area() { return this.r * this.r * Math.PI; }
当我们实现Area
方法时,我们必须使用override
关键字。通过这种方式,我们通知编译器我们重写了一个现有的(继承的)方法。
class Rectangle : Drawing
另一种具体形状是矩形。
private int width; private int height;
Rectangle
定义了两个变量:width
和height
。
public override double Area() { return this.width * this.height; }
Rectangle
提供了它自己的Area
方法实现。
$ dotnet run Circle at x: 12, y: 12, radius: 22 Area of circle: 1520.53084433746 x: 12, y: 45 --------------------- Rectangle at x: 10, y: 20, w: 50 h: 60 Area of rectangle: 3000 x: 10, y: 20
在本文中,我们使用了C#中的抽象类。
列出所有C#教程。