简体   繁体   中英

Child Interface's Load(x) function hides parent interface's Load() function

I have the following generic interface

Public Interface IGenericDAO(Of T As {Class, IEntity})

    Sub Save(entity As T)

    Sub Delete(entity As T)

    Sub Delete(id As Long)

    Function Load(id As Long) As T

    Function Load() As List(Of T)

End Interface

And I'd like to have another one like this

Public Interface IAgendaDAO
    Inherits IGenericDAO(Of Agenda)

    Function Load(isPublished As Boolean, meetingType As MeetingType) As List(Of Agenda)

    Function Load(meetingType As Boolean) As List(Of Agenda)

End Interface

But in this case Compiler says that my Load functions hides my Load function without arguments I can do such thing in C#, Why I can't in VB.NET? What can I do to fix that? Should I name my functions each differently?

Yeah, this is one of the basic choices that a language designer needs to make. A core decision is what exactly should happen when a derived class has a member with the exact same name as a member in the base class. This can hide the inherited base class member and make it difficult to use the base member. And it is risky , a innocent maintenance change might suddenly no longer hide the base member and break existing code.

The C# language designers went for "hide-by-signature". In other words, a method only hides if the base method has the exact same name and the exact same arguments. This is what you are used to and hoped to happen in these interface declarations.

While other languages, like C++ and VB.NET went for "hide-by-name". In other words, a method hides when it has the same name, regardless of what arguments it takes. It is a "less surprises" choice, it is much easier to reason through and maintenance changes are less likely to alter behavior of existing code.

You can see this at work in this sample code:

Class Base
    Sub foo()
    End Sub
End Class

Class Derived
    Inherits Base

    Sub foo(i As Integer)   '' Warning: 'foo' shadows an overloadable member declared in Base
    End Sub

    Shadows Sub foo(d As Double)   '' No warning, Shadows suppresses it
    End Sub
End Class

Sub Main()
    Dim obj = New Derived
    obj.foo()          '' Error!
    Dim base As Base = obj
    base.foo()         '' Okay
End Sub

Do note that this is just a warning, it is not an error. It just foreshadows the potential pain you will inflict on the client code programmer. You can hide the warning easily, put the Shadows keyword in front of the Load() method. But certainly consider avoiding the pain and suffering in the client code and just pick another name so there is never an ambiguity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM