virtualide
關鍵字用於修飾方法、屬性、索引器或事件聲明,而且容許在派生類中重寫這些對象。函數
例如,此方法可被任何繼承它的類重寫。this
(C#參考) 對象
public virtual double Area() 繼承
{ 索引
return x * y;事件
} it
虛擬成員的實現可由派生類中的重寫成員更改 io
調用虛方法時,將爲重寫成員檢查該對象的運行時類型。將調用大部分派生類中的該重寫成員,class
若是沒有派生類重寫該成員,則它多是原始成員。
默認狀況下,方法是非虛擬的。不能重寫非虛方法。
virtual修飾符不能與static、abstract, private或override修飾符一塊兒使用。除了聲明和調用語法不一樣外,虛擬屬性的行爲與抽象方法同樣。在靜態屬性上使用virtual修飾符是錯誤的。 經過包括使用override修飾符的屬性聲明,可在派生類中重寫虛擬繼承屬性。
示例
在該示例中,Dimensions類包含x和y兩個座標和Area()虛方法。不一樣的形狀類,如Circle、Cylinder和Sphere繼承Dimensions類,併爲每一個圖形計算表面積。每一個派生類都有各自的Area()重寫實現。根據與此方法關聯的對象,經過調用正確的Area()實現,該程序爲每一個圖形計算並顯示正確的面積。
在前面的示例中,注意繼承的類Circle、Sphere和Cylinder都使用了初始化基類的構造函數,例如:public Cylinder(double r, double h): base(r, h) {}
這相似於C++的初始化列表。
// cs_virtual_keyword.cs
using System;
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.Are
a());
Console.WriteLine("Area of Sphere = {0:F2}", s.Are
a());
Console.WriteLine("Area of Cylinder = {0:F2}", l.Ar
ea());
}
}
輸出
Area of Circle = 28.27
Area of Sphere = 113.10
Area of Cylinder = 150.80