将对一个对象的引用强制转换为对同一类对象的引用有意义吗



《在VB 2010中启动ASP.NET4》一书包含以下内容:

注意:TaxableProduct继承自Product。

您也可以反向投射--例如,投射一个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)

从应税产品转换为应税产品有意义吗?

假设您有这个继承。。。

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

这意味着TaxableProduct产品
但您不能说产品可征税产品这不是真的

在第二个示例中,您创建了一个Product,因此无法转换为TaxableProduct
如果可能的话,哪个值将在theTaxableProduct 中具有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

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

最新更新