3

有人可以向我解释为什么当我尝试从继承的对象调用基类的构造函数时出现编译器错误吗?我已经包含了我所指内容的简短示例。

Public Class Person
    Public name As String

    Public Sub New()
        name = "John Doe"
    End Sub

    Public Sub New(Name As String)
        name = Name
    End Sub

End Class

Public Class NamedPerson
    Inherits Person

    Public Sub New(FirstName As String, LastName As String)
        name = FirstName & " " & LastName
    End Sub

    'adding this makes it work
    Public Sub New(Name As String)
       MyBase.New(Name)
    End Sub

End Class

'Valid
Dim guy1 As Person = New Person()

'Valid 
Dim guy2 As Person = New Person("John Smith")

'Valid
Dim guy3 As NamedPerson = New NamedPerson("John", "Smith")

'Compiler Error
Dim guy4 As NamedPerson = New NamedPerson("John Smith")
4

1 回答 1

5

子类不从其基类型继承构造函数。子类负责定义它自己的构造函数。此外,它必须确保它定义的每个构造函数都隐式或显式调用基类构造函数或链接到同一类型的另一个构造函数。

有关更多信息,请参阅:实例构造函数

从您的示例课程中,

Public Class NamedPerson
    Inherits Person

    Public Sub New(Name As String)
        MyBase.New(Name)
    End Sub

    Public sub New(FirstName As String, LastName As String)
        name = FirstName & " " & LastName
    End Sub
End Class
于 2012-09-12T03:25:43.670 回答