在这最后一个例子中,我们来看看C#的抽象和多态性。首先我们来定义一下这两个新的术语。抽象(Abstract)通过从多个对象提取出公共部分并把它们并入单独的抽象类中实现。在本例中我们将创建一个抽象类Shape(外形)。每一个外形都拥有返回其颜色的方式,不论是正方形还是圆形、长方形,返回颜色的方式总是一样的,因此这个方式可以提取出来放入父类Shape。这样,假如我们有10个不同的外形需要有返回颜色的方式,现在只需在父类中创建一个方式。可以看到使用抽象使得代码更加简短。 在面向对象编程领域中,多态性(Polymorphism)是对象或者方式根据类的不同而作出不同行为的能力。在下面这个例子中,抽象类Shape有一个getArea()方式,针对不同的外形(圆形、正方形或者长方形)它具有不同的功能。
下面是代码:
public abstract class Shape {
protected string color;
public Shape(string color) {
this.color = color;
}
public string getColor() {
return color;
}
public abstract double getArea();
}
public class Circle : Shape {
private double radius;
public Circle(string color, double radius) : base(color) {
this.radius = radius;
}
public override double getArea() {
return System.Math.PI * radius * radius;
}
}
public class Square : Shape {
private double sideLen;
public Square(string color, double sideLen) : base(color) {
this.sideLen = sideLen;
}
public override double getArea() {
return sideLen * sideLen;
}
}
/*
public class Rectangle : Shape
...略...
*/
public class Example3
{
static void Main()
{
Shape myCircle = new Circle(\"orange\", 3);
Shape myRectangle = new Rectangle(\"red\", 8, 4);
Shape mySquare = new Square(\"green\", 4);
System.Console.WriteLine(\"圆的颜色是\" + myCircle.getColor()
+ \"它的面积是\" + myCircle.getArea() + \".\");
System.Console.WriteLine(\"长方形的颜色是\" + myRectangle.getColor()
+ \"它的面积是\" + myRectangle.getArea() + \".\");
System.Console.WriteLine(\"正方形的颜色是\" + mySquare.getColor()
+ \"它的面积是\" + mySquare.getArea() + \".\");
}
}
返回类别: 教程
上一教程: 一个用c#写的扫描asp源码漏洞的应用程序
下一教程: .NET Framework 中多语言支持的实现
您可以阅读与"C#语言初级入门(3)"相关的教程:
· C#语言初级入门(1)
· C#语言初级入门(4)
· C#语言初级入门(2)
· .NET之ASP Web Application迅速入门(3)
· 使用纯粹的asp+语言制作的栏目治理(三)