How to implement an interface in VB.Net when two methods have the same name but different parameters

纵然是瞬间 提交于 2020-01-03 10:55:22

问题


I am a C# programmer but I have to work with some VB.Net code and I came across a situation where I have two methods on an interface with the same name but different method parameters. When I attempt to implement this interface in a class, VB.Net requires explicitly declaring "Implements MethodName" after the method signature. Since both method names are identical, this is confusing the compiler. Is there a way to get around this sort of problem? I suspect this must be a common occurrence. Any thoughts?

N.B. This was more a case of the programmer not verifying that the interface in question had not changed from underneath him.


回答1:


How is this confusing the compiler? The compiler expects to find an implementation for every method signature, and distinguishes the implementations by their signatures.

If the signatures are identical/undistinguishable (in most cases it means that the arguments are of the same types in the same order) you'll get a design-time error related to the interface, saying that the two methods cannot overload eachother as they have the same signature.

So, in any case, the compiler should not be confused. Should you need further assistance, please attach a code sample - these things are relatively easy to resolve.

Tip: When writing the implementation, as soon as you write down "implements MyInterface" and hit Enter - Visual Studio will create a "skeleton" code of the implementation, which saves you writing the method signatures and correlating them to the interface.

Example code of having two methods with the same name and everythign working well:

Interface MyInterface
    Sub MySub(ByVal arg0 As DateTime)
    Sub MySub(ByVal arg0 As ULong)
End Interface

Class MyImplementation
    Implements MyInterface

    Public Sub MySub(ByVal arg0 As Date) Implements MyInterface.MySub
        ...
    End Sub

    Public Sub MySub(ByVal arg0 As ULong) Implements MyInterface.MySub
        ...
    End Sub
End Class



回答2:


You can make the method private and give it another name.

Like:

 Private Sub SaveImpl(ByVal someEntity As IEntity) Implements IRepository.Save

this will look to the outside like: someRepository.Save



来源:https://stackoverflow.com/questions/2372726/how-to-implement-an-interface-in-vb-net-when-two-methods-have-the-same-name-but

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!