制作内幕 游戏 网站 图标 | 理论 图标在线制作 | 看图软件 访谈活动 | 教程 技术 万年历
当前位置:首页>CG 教 程>网站开发>ASP.NET>

相关文章

推荐文章

     

热门文章

C#语言初级入门(3)

作者:CG谷 出处: 发布时间:2006-07-11 字体: [ ]

在这最后一个例子中,我们来看看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() + ".");
}
}


↑返回顶部   打印本页   关闭窗口↓  
收藏本文到:天极网摘 新浪VIVI 和讯网摘 博彩中心 365Key网摘 poco网摘 狐摘
亿友响享Yeeyoo igooi-it网摘 5seek网摘 I2Key 我摘网摘 天下图摘 YouNote 百特门
用户名: 新注册) 密码: 匿名评论 [所有评论]
评论内容:(不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。
设计服务 | 广告投放 | 友情链接 | 关于本站 | 联系我们 | 版权声明 | 设为首页 | 加入收藏