将对象的引用强制转换为对同一类对象的引用是否有意义?

时间:2012-03-17 11:10:32

标签: vb.net

本书"Beginning ASP .NET 4 in VB 2010"包含以下内容:

注意: TaxableProduct继承自Product。

  

您也可以反向投射 - 例如,施放产品   对TaxableProduct引用的引用。这里的诀窍是这个   仅当内存中的对象确实是TaxableProduct时才有效。   这段代码是正确的:

Dim theProduct As New TaxableProduct(...)
Dim theTaxableProduct As TaxableProduct
theTaxableProduct = CType(theProduct, TaxableProduct)
  

但是这段代码在最后一行产生运行时错误   执行:

Dim theProduct As New Product(...)
Dim theTaxableProduct As TaxableProduct 
theTaxableProduct = CType(theProduct, TaxableProduct)

将TaxableProduct转换为TaxableProduct是否有意义?

2 个答案:

答案 0 :(得分:2)

假设你有这种继承......

Public Class Product
    Dim name As String
---
End Class

Public Class TaxableProduct
     Inherits Product
    Dim taxPct As Single
---
End Class 

这意味着TaxableProduct 产品
但你不能说产品 TaxableProduct。 这不是真的

在您的第二个示例中,您创建了一个产品,因此无法转换为TaxableProduct 如果有可能在theTaxableProduct

中有哪个值包含taxPct

答案 1 :(得分:1)

这称为 upcasting ,它是您有时可以做的最好的。考虑一种情况,在这种情况下,您需要检查特定派生类的方法,并采取适当的措施。例如:

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

如果没有 upcasting ,处理所有产品及其派生类并不容易。