微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

VB.NET 通用接口、基派生类和工厂模式

如何解决VB.NET 通用接口、基派生类和工厂模式

嗨,我在为通用接口创建工厂模式时遇到问题。

我有 IFileHelper(Of T) 接口:

Public Interface IFileHelper(Of T)

   Property ContainsHeader As Boolean

   Function IsValid(path As String) As FileValidationResult

   Function ReadFile(path As String) As List(Of T)

End Interface

我有 CsvFileHelper(Of T),它实现了接口 IFileHelper(Of T)

Public Class CsvFileHelper(Of T)
   Implements IFileHelper(Of T)

       Public Property ContainsHeader As Boolean Implements IFileHelper(Of T).ContainsHeader

       Public Function IsValid(path As String) As Boolean Implements IFileHelper(Of T).IsValid

       End Function

       Public Function ReadFile(path As String) As List(Of T) Implements IFileHelper(Of T).ReadFile

       End Function

End Class

现在我有一个名为 FileModel 的抽象类。

    Public MustInherit Class FileModel

    End Class

以及其他继承抽象类的模型类:

    Public Class CarModel
       Inherits FileModel
       'fields and propeties
    End Class

    Public Class TruckModel
       Inherits FileModel
       'fields and properties
    End Class

Public Shared Function FileFactory(Of FileModel)(ByVal vehicle As VehicleType) As IFileHelper(Of FileModel)

        Select Case vehicle 

            Case VehicleType.Car
                Return CType(New CsvFileHelper(Of CarModel),IFileHelper(Of FileModel))

            Case VehicleType.Truck
                Return CType(New CsvFileHelper(Of TruckModel),IFileHelper(Of FileModel))

            Case Else
                Throw New NotImplementedException("Not implemented for type " & vehicle.ToString.Trim & "!")

        End Select

    End Function

主要方法

Public Sub Main()
 Dim fileHelper As IFileHelper(Of FileModel) = FileFactory(Of FileModel)(VehicleType.Car)
End Main

我已将 Option Strict 设置为 Off 但这无济于事,有什么办法可以使这件事起作用吗?

编辑: 我编辑并使用了@jmcilhinney 在他的回答中显示的工厂方法,但出现运行时错误

Unable to cast object of type 'CsvFileHelper`1[CarModel]' to type 'IFileHelper`1[FileModel]'

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。