程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> C#語言初級入門(3)

C#語言初級入門(3)

編輯:.NET實例教程
在這最後一個例子中,我們來看看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() + ".");
}
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved