vb.net类向上/向下转换

问题描述 投票:0回答:1

我在vb.net中转换类时遇到问题,因为我在处理旧版Windows Mobile项目时将Visual Studio 2008与Compact Framework 3.5一起使用。

我有一个DLL,用作访问SqlCe中数据库对象的数据层,我无法更改其中的任何代码,但是我想为业务逻辑的公开类添加额外的功能,所以我创建了自己的类并且从数据层继承了类]

Public Partial Class Customers
    Public Function ListAll() As IEnumerable(Of Customers)
        'Do Work
    End Function
End Class

Public Class MyCustomers
    Inherits Customers

    Public Function FindCustomer(ID As Integer)
    End Function
End Class

所以在我的代码中,我会写类似

For Each c As MyCustomer In Customers.ListAll
    'I want to be able to use my c.FindCustomer(), but I get an InvalidCast Exception above.
Next

我知道这是向上转换/向下转换的问题(我不记得是哪种方式,但是我该如何解决呢?

我无法更改Customers.ListAll()的返回类型,但我需要能够添加方法和属性以实现业务逻辑。

vb.net compact-framework
1个回答
1
投票

For Each循环内:

一次拍摄:

DirectCast(c, MyCustomer).FindCustomer(1) 'for id 1

要使用多次:

Dim customer as MyCustomer = DirectCast(c, MyCustomer)
customer.FindCustomer(1)

您也可以这样做:

With DirectCast(c, MyCustomer)
    .FindCustomer(1)
    .AnotherMethod()
    'etc
End With

玩得开心!


这里是另一种选择。我不确定您的项目的确切架构,所以我假设是这样的:

Customers      -has a list of Customer
MyCustomers    -child of Customers with a list of MyCustomer and more functionalities

Customer       -base entry
MyCustomer     -base entry with more functionalities

问题是您无法将对象投射到其子对象中(这种操作只能在另一个方向上进行,这基本上是一个不可能的问题。但是,您可以通过克隆来绕过它。这告诉我CustomerMyCustomer的基本数据相同,只添加了更多方法。很好,因为这还意味着您可以将客户手动转换为MyCustomer。您只需要它自动发生。

在MyCustomers和MyCustomer类中,您可以添加以下内容:

'In MyCustomers
Public Shared Function GetMyCustomersFromCustomers(customers As Customers) As MyCustomers
    Dim data As New MyCustomers()
    'copy each modal variable

    'create a list of MyCustomer from existing Customer list
    For Each c As Customer In customers.listOfCustomers
            data.listOfMyCustomers.Add(MyCustomer.GetMyCustomerFromCustomer(c))
    Next

    Return data
End Function

'In MyCustomer
Public Shared Function GetMyCustomerFromCustomer(customer As Customer) As MyCustomer
    Dim data As New MyCustomer

    'copy all the data

    Return data
End Function

然后,如果您想使用自己的对象,则可以从dll中推断出它们:

'let's say you currently have a 'customers' as Customers object
Dim myStuff as MyCustomers = MyCustomers.GetMyCustomersFromCustomers(customers)

如果您经常需要MyCustomers列表,而不关心其余的类,则可以创建一个Shared函数,该函数仅向您提供MyCustomer的推断列表,没问题。

当然,这只有在您可以从客户推断MyCustomer并从客户推断MyCustomer时有效。

希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.