でtaxPctを持っているであろう価値が可能であった場合
はこれがアップキャストと呼ばれ、それはあなたが時々できる最善です。特定の派生クラスをチェックして適切な処置を取る必要のあるメソッド内部の状況を考えてみましょう。たとえば:
Public Class Product
Private productName As String
Public Sub New(ByVal name As String)
productName = name
End Sub
Public ReadOnly Property Name() As String
Get
Return productName
End Get
End Property
End Class
Public Class TaxableProduct
Inherits Product
Public Sub New(ByVal name As String, ByVal value As Decimal)
MyBase.New(name)
productValue = value
End Sub
Private productValue As Decimal
Public Property Value() As Decimal
Get
Return productValue
End Get
Set(ByVal value As Decimal)
productValue = value
End Set
End Property
End Class
Public Class TaxDistrict
Dim districtTaxRate As Decimal
Public Sub New(ByVal taxRate As Decimal)
districtTaxRate = taxRate
End Sub
Public ReadOnly Property TaxRate() As Decimal
Get
Return districtTaxRate
End Get
End Property
Public Function CalculateTax(ByVal theProduct As Product) As Decimal
If TypeOf theProduct Is TaxableProduct Then
' Upcasting is needed to get the value of the product
Dim taxProduct As TaxableProduct = CType(theProduct, TaxableProduct)
Return districtTaxRate * taxProduct.Value
End If
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim cart As New List(Of Product)()
cart.Add(New Product("Tricyle"))
cart.Add(New TaxableProduct("Bicyle", 100.0))
cart.Add(New Product("Candy"))
cart.Add(New TaxableProduct("Lumber", 400.0))
Dim kalamazoo As New TaxDistrict(0.09)
For Each prodInCart As Product In cart
Console.WriteLine("Tax for {0} is {1}", prodInCart.Name, kalamazoo.CalculateTax(prodInCart))
Next
End Sub
End Module
Producing the result
Tax for Tricyle is 0
Tax for Bicyle is 9.00
Tax for Candy is 0
Tax for Lumber is 36.00
アップキャストなければ、すべての製品とその派生クラスを処理することは容易ではなかったであろう。
2番目の例では、 'theProdct'は' TaxableProduct'のインスタンスではなく 'Product'(基本クラス)のインスタンスです。 – ja72