我应该遮蔽还是覆盖?

时间:2013-08-26 11:11:32

标签: vb.net inheritance override shadows

我知道有很多问题和其他网页解释了阴影和覆盖之间的区别。不幸的是,我仍然不明白应该使用哪一个。

我的情况是这样的:我希望创建一个继承特定类型的System.ComponentModel.BindingList的类,以进行添加和删除线程安全等操作。

如果我的基本课程如下:

Imports System.ComponentModel

Public Class DeviceUnderTestBindingList

Inherits System.ComponentModel.BindingList(Of DeviceUnderTest)

Private Sub New()
    MyBase.New()
End Sub

Public Sub Add(ByVal device As DeviceUnderTest)
    MyBase.Add(device)
End Sub

Public Sub Remove(ByVal deviceKey As UInteger)
    MyBase.Remove(deviceKey)
End Sub
End Class

我希望有人使用这个类只能使用我提供的.Add和.Remove方法,而不能使用BindingList中的方法。但我希望我的类能够访问内部的 的BindingList方法,例如你可以看到我的.Add方法当前在某个时候调用了BindingList.Add方法。

我已经尝试过同时使用shadowsoverrides,它们似乎都会产生相同的效果,因此在这种情况下一个比另一个更正确吗?为什么?

2 个答案:

答案 0 :(得分:2)

重载是一个完全不同的概念。从本质上讲,重载允许您使用多个Add()Remove()方法,同时覆盖方法“替换”原始行为。阴影介于两者之间。阴影'隐藏'原始行为,但您仍然可以通过强制转换为基本类型来访问基本方法。

一般来说,如果您可以覆盖它,则不会遮挡成员。除非你有非常具体的理由这样做。

请注意,您不能同时覆盖和隐藏同一个成员。但是,例如,您可以覆盖和重载原始Add()方法。

修改

您无法覆盖Add()方法,但可以覆盖OnAddingNew()。同样,您无法覆盖Remove(),但可以覆盖RemoveItem()。我不知道这门课的具体内容,但我怀疑Remove()使用RemoveItem()

您的实施可能看起来像这样:

Imports System.ComponentModel
Imports System.Collections.ObjectModel

Public Class DeviceUnderTestBindingList
    Inherits BindingList(Of DeviceUnderTest)

    Private Sub New()
        MyBase.New()
    End Sub

#Region "Add()"

    Protected Overrides Sub OnAddingNew(e As AddingNewEventArgs)
        Dim newDevice As DeviceUnderTest = DirectCast(e.NewObject, DeviceUnderTest)

        Try
            If (Not IsValidEntry(newDevice)) Then ' don't add the device to the list
                Exit Sub
            End If

            ' (optionally) run additional code
            DoSomethingWith(newDevice)
        Finally
            MyBase.OnAddingNew(e)
        End Try
    End Sub

    Private Function IsValidEntry(device As DeviceUnderTest) As Boolean
        ' determine whether the specified device should be added to the list
        Return True Or False
    End Function

    Private Sub DoSomethingWith(newDevice As DeviceUnderTest)
        ' This is where you run additional code that you would otherwise put in the 'Add()' method.
        Throw New NotImplementedException
    End Sub

#End Region ' Add()

#Region "Remove()"

    Public Shadows Function Remove(device As DeviceUnderTest) As Boolean
        Try
            RemoveItem(IndexOf(device))
        Catch
            Return False
        End Try
        Return True
    End Function

    Protected Overrides Sub RemoveItem(index As Integer)
        MyBase.RemoveItem(index)
    End Sub

#End Region ' Remove()

End Class

答案 1 :(得分:1)

查看this问题和接受的答案。它解释了C#new& override个关键字,即AFAIK,与VB的含义相同。shadows& overrides

在您的情况下,我建议您使用override。更一般地说,只有在您确定要执行此操作的情况下,才能更好地使用shadows(或C#中的new)。

如果您使用shadows关键字,用户将能够调用方法的基本类型版本 - 而不是您在类中定义的版本 - 以防他们通过基本类型引用调用它。使用overrides,在两种情况下都会调用您的方法版本。