阴影

它重新声明了一个不可覆盖的成员。只有对实例的调用才会受到影响。基类内的代码不受此影响。

Public Class Person
    Public Sub DoSomething()
        Console.WriteLine("Person")
    End Sub

    Public Sub UseMe()
        Me.DoSomething()
    End Sub
End Class
Public Class Customer
    Inherits Person
    Public Shadows Sub DoSomething()
        Console.WriteLine("Customer")
    End Sub

End Class

用法示例:

Dim p As New Person
Dim c As New Customer
p.UseMe()
c.UseMe()
Console.WriteLine("----")
p.DoSomething()
c.DoSomething()

输出:

Person
PersonPerson
Customer

陷阱

Example1,通过泛型创建新对象。将使用哪个功能?

Public Sub CreateAndDoSomething(Of T As {Person, New})()
    Dim obj As New T
    obj.DoSomething()
End Sub

示例用法:

Dim p As New Person
p.DoSomething()
Dim s As New Student
s.DoSomething()
Console.WriteLine("----")
CreateAndDoSomething(Of Person)()
CreateAndDoSomething(Of Student)()

输出:通过直觉,结果应该是相同的。但事实并非如此。

Person
StudentPerson
Person

例 2:

Dim p As Person
Dim s As New Student
p = s
p.DoSomething()
s.DoSomething()

输出:凭直觉你可以认为 p 和 s 相等并且表现相同。但事实并非如此。

Person
Student

在这个简单的例子中,很容易学习 Shadows 的奇怪行为。但在现实生活中它带来了许多惊喜。最好是防止使用阴影。人们应该尽可能多地使用其他替代品(覆盖等)