如何将 'especific' 类型的对象转换为在多记录中键入 'FileHelpers.Events.INotifyRead

How to cast object of type 'especific' to type 'FileHelpers.Events.INotifyRead in Multirecording

我试图将所有格式和转换规则集中在一个 class 特定的。使用接口 INotifyRead(Of T As Class)。当我实现方法时 BeforeRead/AfterRead 抛出异常:无法将类型 'Especific' 的对象转换为类型 'FileHelpers.Events.INotifyRead`1[System.Object]'.

下面是我的代码。

Using engine As New MultiRecordEngine(New RecordTypeSelector(AddressOf CifraRecordTypeSelector),
                                                GetType(RemessaRegistroCliente),
                                                GetType(RemessaRegistroContrato))
    Dim records = engine.ReadFile(_camArquivo)
End Using

Public NotInheritable Class RemessaRegistroCliente
    Implements INotifyRead(Of RemessaRegistroCliente)

    Public Sub AfterRead(e As AfterReadEventArgs(Of RemessaRegistroCliente)) Implements INotifyRead(Of RemessaRegistroCliente).AfterRead

    End Sub

    Public Sub BeforeRead(e As BeforeReadEventArgs(Of RemessaRegistroCliente)) Implements INotifyRead(Of RemessaRegistroCliente).BeforeRead

    End Sub
End Class

Public NotInheritable Class RemessaRegistroContrato
    Implements INotifyRead(Of RemessaRegistroContrato)

    Public Sub AfterRead(e As AfterReadEventArgs(Of RemessaRegistroContrato)) Implements INotifyRead(Of RemessaRegistroContrato).AfterRead

    End Sub

    Public Sub BeforeRead(e As BeforeReadEventArgs(Of RemessaRegistroContrato)) Implements INotifyRead(Of RemessaRegistroContrato).BeforeRead

    End Sub
End Class

由于 MultiRecordEngine 没有通用版本,您无法实现通用 INotifyRead(Of T) 来处理事件。相反,将委托分配给引擎。

Sub Main()
    Using engine As New MultiRecordEngine(New RecordTypeSelector(AddressOf CifraRecordTypeSelector),
                                                GetType(RemessaRegistroCliente),
                                                GetType(RemessaRegistroContrato))
        AddHandler engine.BeforeReadRecord, AddressOf BeforeReadRecordHandler
    End Using
End Sub

Private Sub BeforeReadRecordHandler(ByVal engine As EngineBase, ByVal e As BeforeReadEventArgs(Of Object))

End Sub

您还需要修改 类 以删除通用接口:

Public NotInheritable Class RemessaRegistroCliente
   'your fields
End Class

Public NotInheritable Class RemessaRegistroContrato
   'your fields
End Class