问题描述
嗨,我在为通用接口创建工厂模式时遇到问题。
我有 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
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 (将#修改为@)