使用重载的小例子:这是编译器错误吗?

时间:2011-03-23 19:03:02

标签: .net vb.net visual-studio-2008

在这种情况下,VB.NET编译器如何确定调用哪个函数?

对我而言,似乎它应该引发错误,因为它无法分辨(或者至少这对我来说是什么。)

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 String) 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

2 个答案:

答案 0 :(得分:1)

第一个将被调用。一般来说,编译器更喜欢比更通用的方法更具体的方法。

另一个例子:

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"

答案 1 :(得分:0)

这些功能有不同的签名。 paramarray类型与字符串类型不同。