开发者

Small example using Overloading: Is this a compiler bug?

How does the VB.NET compiler in this case determine which function is being called?

To me, it seems like it should raise an error because it CAN'T tell (or at least that's what it seems to me.)

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        MessageBox.Show(Function1("A", "B", "C", "D"))
    End Sub
    Private Overloads Function Function1(ByVal x As String, ByVal y As String, ByVal ParamArray z() As S开发者_C百科tring) As String
        Return "1"
    End Function
    Private Overloads Function Function1(ByVal x As String, ByVal ParamArray z() As String) As String
        Return "2"
    End Function

End Class


The first one will be called. In general, the compiler will prefer the more specific method over the more general one.

Another example:

Class Parent
End Class

Class Child
    Inherits Parent
End Class

...

Private Overloads Sub Function1(ByRef obj As Object)
    MessageBox.Show("Object")
End Sub
Private Overloads Sub Function1(ByRef parent As Parent)
    MessageBox.Show("Parent")
End Sub
Private Overloads Sub Function1(ByRef child As Child)
    MessageBox.Show("Child")
End Sub

...

Function1(New Child())  'Displays "Child"
Function1(New Parent()) 'Displays "Parent"
Function1(10)           'Displays "Object"
Function1(DirectCast(New Parent(), Object)) 'Displays "Object"


The functions have different signatures. A paramarray type is not the same as a string type.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜