当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > C#语言初级入门(3)

ASP.NET
如何在ASP.NET中使用SmtpMail发送邮件
在VB.NET中利用Split和Replace函数计算字数
Attribute应用:简化ANF自定义控件初始化过程
ASP.NET 2.0移动开发入门之使用样式
ASP.NET 2.0中使用OWC生成图表
ASP.NET 2.0中控件的简单异步回调
一个无法捕获ADO.NET Dataset的内存错误
深入解读ADO.NET2.0的十大最新特性
.Net平台下的分布式缓存设计
ASP.NET全局异常处理浅析
ASP.NET 2.0中文验证码的实现
浅析.NET平台编程语言的未来走向
.net 框架程序设计收藏
使用ASP.NET MVC Futures 中的异步Action
详解.NET中的XmlReader与XmlWriter
关于.NET中的Server push技术
asp.net页面执行机制
对比JSP和ASP.NET的存储过程
.NET 4.0不会包含System.Shell.CommandLine
ASP.NET十个有效性能优化的方法

ASP.NET 中的 C#语言初级入门(3)


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-11-03   浏览: 181 ::
收藏到网摘: n/a

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