如何跨子类保留 'New' 构造函数?

How to retain the 'New' constructor across subclasses?

让我们从一个示例模块开始:

Module PuppyKillers
    Public Puppies As Double = 135
    Public SquadSize As Integer = 5
    Class PuppyKiller
        Private KillingTimer As New System.Timers.Timer _
            With {.AutoReset = True, .Interval = 1000, .Enabled = False}
        Public PuppiesPerSecond As Double = 0.5
        Public name As String = "John Doe"
        Public Sub New(Optional param As Double = 1)
            PuppiesPerSecond = PuppiesPerSecond * param
            AddHandler KillingTimer.Elapsed, AddressOf KillPuppies
        End Sub
        Private Sub KillPuppies(ByVal sender As Object, _
                                ByVal e As System.Timers.ElapsedEventArgs)
            If Puppies <= 0 Then
                Me.Killing = False
            Else
                Puppies -= PuppiesPerSecond
            End If
        End Sub

        Property Killing As Boolean
            Get
                Return KillingTimer.Enabled
            End Get
            Set(value As Boolean)
                KillingTimer.Enabled = value
            End Set
        End Property
    End Class

    Class ChiefPuppyKiller
        Inherits PuppyKiller
    End Class

    Sub Exterminators_Start() ' 4 Killers + 1 Chief
        Dim squad As New ArrayList

        REM The following line prevents the compilation.
        squad.Add(New ChiefPuppyKiller(3)) 'A chief kills 3 times the normal amount.

        For i As Integer = 1 To SquadSize - 1
            squad.Add(New PuppyKiller)
        Next

        REM Start the slaughter
        Console.WriteLine("Puppies: " & Puppies)
        For Each c As PuppyKiller In squad
            c.Killing = True
        Next
        Do
            Threading.Thread.Sleep(4737)
            Console.WriteLine("Remaining Puppies: " & Math.Ceiling(Puppies))

            Application.DoEvents()
            If Puppies = 0 Then
                Console.WriteLine("Meow: No more puppies.")
                Exit Do
            End If
        Loop
    End Sub
End Module

上面的代码块有问题:我找不到从其子classes 中使用PuppyKiller 的构造函数的方法:在这种情况下为ChiefPuppyKiller .

我得到关于构造函数的参数数量的错误,所以我假设未使用基础 class 构造函数。

我不想为每个子 class 声明一个新的 New 子。但我希望能够在构造函数中指定杀死小狗的乘数。


注意:由于代码无法编译,因此在编写此问题时没有动物受到伤害。

您将不得不为每个 class 添加一个新的构造函数,其中您希望将值传递给:

Class ChiefPuppyKiller
  Inherits PuppyKiller

  Public Sub New(param As Double)
    MyBase.New(param)
  End Sub
End Class