Is the 'Overloads' keyword ever required in VB.Net?

假如想象 提交于 2021-01-29 04:57:34

问题


As the title says. From what I can see online the Overloads keyword is optional but is there ever a time when it is necessary? It even seems to be an error when used in a Module.


回答1:


No, it's not neccessary. You can overload methods and properties without the Overloads keyword.

However, if you use the Overloads or Overrides keyword on one overload of a method, you have to use it on all other overloads to that method in the class.

You can use the Overloads keyword instead of the Shadows keyword to shadow an inherited method with the same signature. Then you have to use either of the keywords, they are not both optional.




回答2:


There is only one case where the keyword Overloads is mandatory. If a method has the keyword Overloads then any new method of the same name within the type must also have Overloads

Other than that case, the keyword is optional.




回答3:


you don’t have to use the Overloads keyword to specify an overloaded method while within the same class. This is how C# handles overloading – there is no Overloads keyword in C#.
But using the Overloads keyword, tends to be more readable.
Check out this blog post for more detailed information.




回答4:


In the interest of accuracy, I'm making this very late response since I noticed that the existing answers are simply incorrect. 'Overloads' is certainly required in a few cases, most commonly when another method of the same name overrides a base class method, as in the following example - the code simply will not compile if the 'Overloads' keyword is removed:

Public Class One
    Public Overridable Sub method()
    End Sub
End Class
Public Class Two
    Inherits One

    Public Overrides Sub method()
    End Sub

    Public Overloads Sub method(ByVal i As Integer)
    End Sub
End Class



回答5:


Weirdly, there are times when you can't use the Overloads keyword. For example:

Module MyModule
    Overloads Sub MySub(Param1 As String)
    End Sub
    Overloads Sub MySub(Param1 As String, Param2 As Integer)
    End Sub
End Module

The compiler throws error, "Inappropriate use of 'Overloads' keyword in a module".

Not sure why, as you can still overload the method as usual.



来源:https://stackoverflow.com/questions/4038032/is-the-overloads-keyword-ever-required-in-vb-net

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