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 ;
来源:https://www.cnblogs.com/a-dou/p/5744963.html