如何使用 FileHelpers 分隔具有不同 RowType 的行?

How can I separate rows with different RowTypes using FileHelpers?

例如,我的下一个文件 test.txt 有两行:

Type00007P 008 PPL

Type00230J 190 1

我代码中接下来的 class 使用 Rhino-ETL Nuget 在我的数据库中插入这些行:

public class Type00007P
{
    [FieldFixedLength(10)]
    [FieldTrim(TrimMode.Both)]
    public string TypeControl;

    [FieldFixedLength(3)]
    [FieldTrim(TrimMode.Both)]
    public int Id;

    [FieldFixedLength(3)]
    [FieldTrim(TrimMode.Both)]
    public string Name;
}


public class Type00230J
{
    [FieldFixedLength(10)]
    [FieldTrim(TrimMode.Both)]
    public string TypeControl;

    [FieldFixedLength(3)]
    [FieldTrim(TrimMode.Both)]
    public int Id;

    [FieldFixedLength(1)]
    [FieldTrim(TrimMode.Both)]
    public bool Calculated;
}

如果我使用下一个代码提取行,我无法区分同一文件中的行 Type00007P 和行 Type00230J:

public override IEnumerable<Row> Execute(IEnumerable<Row> rows)
{
    using (FileEngine file = FluentFile.For<Type00007P>().From(FilePath))
    {
        foreach (object obj in file)
        {
            yield return Row.FromObject(obj);
        }
    }
}

那么,我如何读取第一个固定字段以获取 RowType,然后用正确的 class 处理整行?

此致!

可以使用MultiRecordEngine。文档是 here.

var engine = new MultiRecordEngine(
    typeof(Type00007P),
    typeof(Type00230J));

engine.RecordSelector = new RecordTypeSelector(CustomSelector);

然后定义一个CustomSelector.

private Type CustomSelector(MultiRecordEngine engine, string recordLine)
{
    if (recordLine.Length == 0)
        return null;

    if (recordLine.StartsWith("Type00007P")))
        return typeof(Type00007P);
    else
        return typeof(Type00230J);
}