VB.NET中的"Overloads"关键字

16 vb.net methods

你真的需要这个关键字来重载方法吗?使用overloads关键字与仅使用不同的方法签名有什么区别?

Kei*_*ley 17

这显示了谷歌搜索结果的高位,我认为这里可以更清楚地解释.

Overloads当您在同一个类中重载各种方法时,没有理由使用该关键字.您将使用的主要原因Overloads是允许派生类从其基类调用方法,该方法与重载方法具有相同的名称,但具有不同的签名.

假设你有两个类,Foo并且从SonOfFoo哪里SonOfFoo继承Foo.如果Foo实现一个名为的方法DoSomethingSonOfFoo实现具有相同名称的SonOfFoo方法,该方法将隐藏父类的实现...即使这两个方法采用不同的参数.指定Overloads关键字将允许派生类调用父类的方法重载.

下面是一些代码来演示上面的内容,使用所描述的类FooSonOfFoo实现,以及另一对类,BarSonOfBar使用Overloads关键字:

Class Foo
    Public Sub DoSomething(ByVal text As String)
        Console.WriteLine("Foo did: " + text)
    End Sub
End Class

Class SonOfFoo
    Inherits Foo

    Public Sub DoSomething(ByVal number As Integer)
        Console.WriteLine("SonOfFoo did: " + number.ToString())
    End Sub
End Class

Class Bar
    Public Sub DoSomething(ByVal text As String)
        Console.WriteLine("Bar did: " + text)
    End Sub
End Class

Class SonOfBar
    Inherits Bar

    Public Overloads Sub DoSomething(ByVal number As Integer)
        Console.WriteLine("SonOfBar did: " + number.ToString())
    End Sub
End Class

Sub Main()
    Dim fooInstance As Foo = New SonOfFoo()
    'works
    fooInstance.DoSomething("I'm really a SonOfFoo")
    'compiler error, Foo.DoSomething has no overload for an integer
    fooInstance.DoSomething(123)

    Dim barInstance As Bar = New SonOfBar()
    'works
    barInstance.DoSomething("I'm really a SonOfBar")
    'compiler error, Bar.DoSomething has no overload for an integer
    barInstance.DoSomething(123)

    Dim sonOfFooInstance As New SonOfFoo()
    'compiler error, the base implementation of DoSomething is hidden and cannot be called
    sonOfFooInstance.DoSomething("I'm really a SonOfFoo")
    'works
    sonOfFooInstance.DoSomething(123)

    Dim sonOfBarInstance As New SonOfBar()
    'works -- because we used the Overloads keyword
    sonOfBarInstance.DoSomething("I'm really a SonOfBar")
    'works
    sonOfBarInstance.DoSomething(123)
End Sub
Run Code Online (Sandbox Code Playgroud)

以下是有关如何在CLI中进行不同编译的一些信息.

  • 我一定是世界上最健忘的人; 我是从谷歌搜索来到这里的,当我看到自己的答案时,他最终砸了自己的脸. (20认同)

Pat*_*ald 16

在同一个类中,Overloads关键字是可选的,但如果一个方法声明Overloads或者Overrides,你必须将它用于该方法的所有重载.

' this is okay
Sub F1(s as String)
Sub F1(n as Integer)

' This is also okay
Overloads Sub F2(s as String)
Overloads Sub F2(n as Integer)

' Error
Overloads Sub F3(s as String)
Sub F3(n as Integer)
Run Code Online (Sandbox Code Playgroud)

但是,当您在派生类中重载基类方法时,它会变得更加复杂.

如果基类有多个重载方法,并且您希望在派生类中添加重载方法,则必须使用Overloads关键字在派生类中标记该方法,否则基类中的所有重载方法在派生类中都不可用.

有关详细信息,请参阅MSDN.


Mik*_*scu 9

这是一个设计考虑因素.当然它(VB)可能被设计为通过函数签名推断过载(比如在C#中) - 所以Overloads关键字本身可能已被省略但最终它符合Visual Basic的表达性(有些人认为是开销)这只是一个语言设计决定.

  • @Adrian Godong:OP询问VB中是否需要"Overloads"关键字 - 而不是重载是否有用(而不是仅仅使用不同的方法名称) (4认同)