您现在的位置:软界网技术中心软件开发C# > 技术显示
C#语言初级基础教程(3)
2008-2-22 10:12:00   网友评论       阅读次数 点此评论
   在这最后一个例子中,我们来看看C#的抽象和多态性。首先我们来定义一下这两个新的术语。抽象(Abstract)通过从多个对象提取出公共部分并把它们并入单独的抽象类中实现。在本例中我们将创建一个抽象类Shape(形状)。每一个形状都拥有返回其颜色的方法,不论是正方形还是圆形、长方形,返回颜色的方法总是相同的,因此这个方法可以提取出来放入父类Shape。这样,如果我们有10个不同的形状需要有返回颜色的方法,现在只需在父类中创建一个方法。可以看到使用抽象使得代码更加简短。

   在面向对象编程领域中,多态性(Polymorphism)是对象或者方法根据类的不同而作出不同行为的能力。在下面这个例子中,抽象类Shape有一个getArea()方法,针对不同的形状(圆形、正方形或者长方形)它具有不同的功能。

   下面是代码:

软件开发网 www.mscto.cn


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() ".");
}
}

 
      来源: 作者:
 
【评论查看】