Kei*_*ley 17
这显示了谷歌搜索结果的高位,我认为这里可以更清楚地解释.
Overloads当您在同一个类中重载各种方法时,没有理由使用该关键字.您将使用的主要原因Overloads是允许派生类从其基类调用方法,该方法与重载方法具有相同的名称,但具有不同的签名.
假设你有两个类,Foo并且从SonOfFoo哪里SonOfFoo继承Foo.如果Foo实现一个名为的方法DoSomething并SonOfFoo实现具有相同名称的SonOfFoo方法,该方法将隐藏父类的实现...即使这两个方法采用不同的参数.指定Overloads关键字将允许派生类调用父类的方法重载.
下面是一些代码来演示上面的内容,使用所描述的类Foo和SonOfFoo实现,以及另一对类,Bar并SonOfBar使用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中进行不同编译的一些信息.
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.
这是一个设计考虑因素.当然它(VB)可能被设计为通过函数签名推断过载(比如在C#中) - 所以Overloads关键字本身可能已被省略但最终它符合Visual Basic的表达性(有些人认为是开销)这只是一个语言设计决定.