c# virtual

cyang812 Lv6

Virtual

The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class.

When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.

By default, methods are non-virtual. You cannot override a non-virtual method.

Benefit

By using virtual, when the base class instance called the method, the most drived class’s method will be executed.

1
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
72
73
74
75
76
77
78
79
80
81
82
using System;

class Example
{
static void Main()
{
Foo f = new Foo();
f.M();

Foo b = new Bar();
b.M();

Foo barHiden = new BarHiden();
barHiden.M();

BarHiden barHiden1 = new BarHiden();
barHiden1.M();

FooVirtual barHidenVirtual = new BarHidenVirtual();
barHidenVirtual.M();

FooVirtual barInheritVirtual = new BarInheritVirtual();
barInheritVirtual.M();

BarInheritVirtual barInheritVirtual1 = new BarInheritVirtual();
barInheritVirtual1.M();

BarHidenVirtual barHidenVirtual1 = new BarHidenVirtual();
barHidenVirtual1.M();

FooVirtual barHidenVirtual2 = barHidenVirtual1;
barHidenVirtual2.M();
}
}

class Foo
{
public void M()
{
Console.WriteLine("Foo.M");
}
}

class FooVirtual
{
public virtual void M()
{
Console.WriteLine("FooVirtual.M");
}
}

class Bar : Foo
{
public void M()
{
Console.WriteLine("Bar.M");
}
}

class BarHiden : Foo
{
public new void M()
{
Console.WriteLine("BarHiden.M");
}
}

class BarInheritVirtual : FooVirtual
{
public override void M()
{
Console.WriteLine("BarInheritVirtual.M");
}
}

class BarHidenVirtual : FooVirtual
{
public new void M()
{
Console.WriteLine("BarHidenVirtual.M");
}
}

1
2
3
4
5
6
7
8
9
Foo.M
Foo.M
Foo.M
BarHiden.M
FooVirtual.M
BarInheritVirtual.M
BarInheritVirtual.M
BarHidenVirtual.M
FooVirtual.M

try.dot.net

  • 标题: c# virtual
  • 作者: cyang812
  • 创建于 : 2022-12-13 12:55:23
  • 更新于 : 2022-12-13 12:55:23
  • 链接: https://blog.cyang.tech/2022/12/13/csharp virtual/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论
目录
c# virtual