陰影

它重新宣告瞭一個不可覆蓋的成員。只有對例項的呼叫才會受到影響。基類內的程式碼不受此影響。

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 的奇怪行為。但在現實生活中它帶來了許多驚喜。最好是防止使用陰影。人們應該儘可能多地使用其他替代品(覆蓋等)