让我们从示例模块开始:
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
我对上面的代码块有疑问:在这种情况下,我找不到从其子类PuppyKiller
使用ChiefPuppyKiller
的构造函数的方法。
我得到了关于构造函数的参数数量的错误,所以我假设没有使用基类构造函数。
我不想为每个子类声明一个新的New
子。但我希望能够在构造函数中指定小狗杀死倍数。
注意:编写此问题时没有动物受到伤害,因为代码无法编译。
答案 0 :(得分:1)
您必须为要传递该值的每个类添加新的构造函数:
Class ChiefPuppyKiller
Inherits PuppyKiller
Public Sub New(param As Double)
MyBase.New(param)
End Sub
End Class