43

在下面的代码中,我收到编译错误

Error Too many arguments to 'Public Sub New()'

Dim TestChild As ChildClass = New ChildClass("c")TestChild.Method1()即使它们都在我继承的基类上,我也没有收到它。

Public Class BaseClass
    Public ReadOnly Text As String
    Public Sub New(ByVal SetText As String)
        Text = SetText
    End Sub
    Public Sub New()
        Text = ""
    End Sub
End Class

Public Class ChildClass
    Inherits BaseClass
End Class

Public Class TestClass
    Sub Test()
        Dim TestChild As ChildClass = New ChildClass("c")
        TestChild.Method1()
    End Sub
End Class

我可以将子类更改为:

Public Class ChildClass
    Inherits BaseClass
      Public Sub New (ByVal SetText As String)
      MyBase.New(SetText)
    End Class
End Class

正如下面所建议的,但我不必为方法 1 或其他继承的方法这样做,我正在寻找尽可能干净的代码。这可能是系统中继承参数化 New 语句的限制,但我无法在任何地方找到它的文档。如果需要,那么我想查看文档。

4

2 回答 2

59

The behavior that you are seeing is "By Design". Child classes do not inherti constructors from their base types. A child class is responsible for defining it's own constructors. Additionally it must ensure that each constructor it defines either implicitly or explicitly calls into a base class constructor or chains to another constructor in the same type.

You will need to define the same constructor on all of the child classes and explicitly chain back into the base constructor via MyBase.New. Example

Class ChildClass
  Inherits BaseClass
  Public Sub New(text As String)
    MyBase.New(text)
  End Sub
End Class

The documentation you are looking for is section 9.3.1 of the VB Language specification.

I think the most relevant section is the following (roughly start of the second page)

If a type contains no instance constructor declarations, a default constructor is automatically provided. The default constructor simply invokes the parameterless constructor of the direct base type.

This does not explicitly state that a child class will not inherit constructors but it's a side effect of the statement.

于 2009-04-26T00:35:18.043 回答
8

参数化构造函数不能像实例方法一样被继承。您需要在子类中实现构造函数,然后使用 MyBase 调用父类的构造函数。

Public Class ChildClass
    Inherits BaseClass

    Public Sub New (ByVal SetText As String)
      MyBase.New(SetText)
    End Class
End Class

Public Class TestClass
  Public TestChild AS New ChildClass("c")
End Class

This limitation is not VB specific. From what I can gather, it's definately not possible in C#, Java or C++ either.

Here is one related post with the same question about C++:
c-superclass-constructor-calling-rules

于 2009-04-25T22:45:17.980 回答