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

2

3

4

调用虚方法时,将为重写成员检查该对象的运行时类型。将调用大部分派生类中的该重写成员,如果没有派生类重写该成员,则它可能是原始成员。
默认情况下,方法是非虚拟的。不能重写非虚方法。
virtual 修饰符不能与 static、abstract 和 override 修饰符一起使用。
除了声明和调用语法不同外,虚拟属性的行为与抽象方法一样。
-
在静态属性上使用 virtual 修饰符是错误的。
-
通过包括使用 override 修饰符的属性声明,可在派生类中重写虚拟继承属性。
在该示例中,Dimensions
类包含 x
和 y
两个坐标和 Area()
虚方法。不同的形状类,如 Circle
、Cylinder
和 Sphere
继承 Dimensions
类,并为每个图形计算表面积。每个派生类都有各自的 Area()
重写实现。根据与此方法关联的对象,通过调用正确的 Area()
实现,该程序为每个图形计算并显示正确的面积。
1
// cs_virtual_keyword.cs
2
using System;
3
class TestClass
4
{
5
public class Dimensions
6
{
7
public const double PI = Math.PI;
8
protected double x, y;
9
public Dimensions()
10
{
11
}
12
public Dimensions(double x, double y)
13
{
14
this.x = x;
15
this.y = y;
16
}
17
18
public virtual double Area()
19
{
20
return x * y;
21
}
22
}
23
24
public class Circle : Dimensions
25
{
26
public Circle(double r) : base(r, 0)
27
{
28
}
29
30
public override double Area()
31
{
32
return PI * x * x;
33
}
34
}
35
36
class Sphere : Dimensions
37
{
38
public Sphere(double r) : base(r, 0)
39
{
40
}
41
42
public override double Area()
43
{
44
return 4 * PI * x * x;
45
}
46
}
47
48
class Cylinder : Dimensions
49
{
50
public Cylinder(double r, double h) : base(r, h)
51
{
52
}
53
54
public override double Area()
55
{
56
return 2 * PI * x * x + 2 * PI * x * y;
57
}
58
}
59
60
static void Main()
61
{
62
double r = 3.0, h = 5.0;
63
Dimensions c = new Circle(r);
64
Dimensions s = new Sphere(r);
65
Dimensions l = new Cylinder(r, h);
66
// Display results:
67
Console.WriteLine("Area of Circle = {0:F2}", c.Area());
68
Console.WriteLine("Area of Sphere = {0:F2}", s.Area());
69
Console.WriteLine("Area of Cylinder = {0:F2}", l.Area());
70
}
71
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71
