在FileHelpers中保留只读属性中的值

时间:2018-10-10 08:33:36

标签: c# filehelpers

FileHelpers是否可以存储任何只读属性?

我认为会有一个使用FileHelpers字段属性的解决方案,但是这样的属性似乎不存在。 (只是存在相反的FieldHidden属性)。

情况(代码)如下

[DelimitedRecord(";")]
public class MigrationFlags
{
    public const string HostUrlTemplate = "{HostUrl}";
    public MigrationFlags()
    {
    }

    [FieldHidden]
    public string Url { get; set; }

    [FieldCaption("RelativeUrl " + HostUrlTemplate)]
    public string RelativeUrl => UriExt.GetRelativeUrl(this.Url);

在这里,我需要添加RelativeUrl。

在我看来,也可以在Url属性上使用转换器,但是是否可以使用其他解决方案,使我可以从名为RelativeUrl的现有属性中受益?

1 个答案:

答案 0 :(得分:0)

除了指定CSV文件的格式外,不建议将FileHelpers类用于任何其他用途。该类表示该文件中的一条记录。将MigrationFlags类的语法视为描述FileHelpers可以自动读取和写入的记录的巧妙方法。

如果需要添加 any 进一步的逻辑,则应将其放在一个单独的类中,必要时可以映射到该类。这可以将关注点分开-MigrationFlags定义CSV记录。

[DelimitedRecord(";")]
public class MigrationFlags
{   
    // Extremely simple class.
    // Only the fields in the CSV
    // No logic. Nothing clever.
    public string RelativeUrl { get; set;};
}

public class MigrationClass
{   
    // A normal C# class with:
    //   constructors
    //   properties
    //   methods
    //   readonly, if you like
    //   inheritance, overrides, if you like
    // etc.

    public string Url { get; set; }
    public string RelativeUrl => UriExt.GetRelativeUrl(this.Url);
}

然后导出,类似于:

public void Export(IEnumerable<MigrationClass> items, string filename)
{ 
    var migrationFlags = items.Select(
        x => new MigrationFlags() 
           { 
             RelativeUrl = x.RelativeUrl,
             // etc.
           });

    var engine = new FileHelperEngine<MigrationFlags>();
    engine.WriteFile(filename, migrationFlags);
}

有关更多信息,请参见this answer