virtual 修飾符 C# .NET


virtual

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

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

(C#參考) 

1 public virtual double Area() 
2 
3 { 
4 
5     return x * y;
6 
7 } 

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

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

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

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

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++的初始化列表。

  1 // cs_virtual_keyword.cs
  2 
  3 using System;
  4 
  5 class TestClass
  6 
  7 { 
  8 
  9     public class Dimensions
 10 
 11     { 
 12 
 13         public const double PI = Math.PI;
 14 
 15         protected double x, y;
 16 
 17         public Dimensions()         {
 18 
 19         } 
 20 
 21         public Dimensions(double x, double y)        { 
 22 
 23             this.x = x;
 24 
 25             this.y = y;
 26 
 27         } 
 28 
 29         public virtual double Area()        { 
 30 
 31             return x * y;
 32 
 33         }
 34 
 35     }
 36 
 39     public class Circle : Dimensions    { 
 40 
 41         public Circle(double r) : base(r, 0)
 42 
 43         {
 44 
 45         }
 46 
 47  
 48 
 49         public override double Area()
 50 
 51         { 
 52 
 53             return PI * x * x;
 54 
 55         }
 56 
 57     }
 58 
 59  
 60 
 61     class Sphere : Dimensions
 62 
 63     { 
 64 
 65         public Sphere(double r) : base(r, 0)
 66 
 67         {
 68 
 69         }
 70 
 71  
 72 
 73         public override double Area()
 74 
 75         { 
 76 
 77             return 4 * PI * x * x;
 78 
 79         }
 80 
 81     }
 82 
 85     class Cylinder : Dimensions
 86 
 87     { 
 88 
 89         public Cylinder(double r, double h) : base(r, h)
 90 
 91         {
 92 
 93         } 
 94 
 95         public override double Area()
 96 
 97         { 
 98 
 99             return 2 * PI * x * x + 2 * PI * x * y;
100 
101         }
102 
103     }
104 
107     static void Main()
108 
109     { 
110 
111         double r = 3.0, h = 5.0; 
112 
113         Dimensions c = new Circle(r);
114 
115         Dimensions s = new Sphere(r); 
116 
117         Dimensions l = new Cylinder(r, h);
118 
119         // Display results: 
120 
121         Console.WriteLine("Area of Circle   = {0:F2}", c.Area()); 
124 
125         Console.WriteLine("Area of Sphere   = {0:F2}", s.Area()); 
128 
129         Console.WriteLine("Area of Cylinder = {0:F2}", l.Area());
132 
133     }
134 
135 } 

輸出 

1 Area of Circle   = 28.27;
2 
3 Area of Sphere   = 113.10;
4 
5 Area of Cylinder = 150.80 ;

 


免責聲明!

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



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