關於virtual(虛擬)

在C#中 ~

要讓子類別複寫的 value or function

必須宣告程 virtual

複寫利用 override

example:

class TestClass
{
public class Dimensions
{
public const double PI = Math.PI;
protected double x, y;
public Dimensions()
{
}
public Dimensions(double x, double y)
{
this.x = x;
this.y = y;
}

public virtual double Area()
{
return x * y;
}
}

public class Circle : Dimensions
{
public Circle(double r) : base(r, 0)
{
}

public override double Area()
{
return PI * x * x;
}
}

class Sphere : Dimensions
{
public Sphere(double r) : base(r, 0)
{
}

public override double Area()
{
return 4 * PI * x * x;
}
}

class Cylinder : Dimensions
{
public Cylinder(double r, double h) : base(r, h)
{
}

public override double Area()
{
return 2 * PI * x * x + 2 * PI * x * y;
}
}

static void Main()
{
double r = 3.0, h = 5.0;
Dimensions c = new Circle(r);
Dimensions s = new Sphere(r);
Dimensions l = new Cylinder(r, h);
// Display results:
Console.WriteLine("Area of Circle = {0:F2}", c.Area());
Console.WriteLine("Area of Sphere = {0:F2}", s.Area());
Console.WriteLine("Area of Cylinder = {0:F2}", l.Area());
}
}
/*
Output:
Area of Circle = 28.27
Area of Sphere = 113.10
Area of Cylinder = 150.80
*/
 
說明網頁 http://msdn.microsoft.com/zh-tw/library/9fkccyh4.aspx

沒有留言:

張貼留言