virtual 修飾符 C# .NET


virtual

 關鍵字用於修飾方法、屬性、索引器或事件聲明,並且允許在派生類中重寫這些對象。

例如,此方法可被任何繼承它的類重寫。

(C#參考) 

public virtual double Area() 

    return x * y;

虛擬成員的實現可由派生類中的重寫成員更改 

調用虛方法時,將為重寫成員檢查該對象的運行時類型。將調用大部分派生類中的該重寫成員,

如果沒有派生類重寫該成員,則它可能是原始成員。 

默認情況下,方法是非虛擬的。不能重寫非虛方法。 

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 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM