开发者

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

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开发者_JS百科 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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜