c# - 使用 csvHelper 序列化子类

标签 c# csvhelper

我想在我的 CSV 输出中包含子类的值。子类包含几个指示可用操作的 bool 值。

public class AllowedActions {
    public bool CanCheckIn { get; set; }
    public bool CanCheckOut { get; set; }
}

public class ContentItem {
    public AllowedActions Actions { get; set; }
    public Guid? ContentTypeId { get; set; }
}

我能否创建一个包含 ContentItem 属性和 AllowedAction 类值的类映射?将它们添加到 map 会导致“未为类型‘XYZ.ContentItem’定义属性‘Boolean CanCheckIn’”错误。

这行不通:

        Map(m => m.Actions.CanCheckIn);
        Map(m => m.Actions.CanCheckOut);

最佳答案

我想通了。为了正确映射子类的成员,我需要使用 References 而不是 Map,并提供一个单独的映射对象,如下所示:

        References<AllowedActionsClassMap>(m => m.Actions);

...

public sealed class AllowedActionsClassMap: CsvClassMap<AllowedActions>
{
    public AllowedActionsClassMap()
    {
        Map(m => m.CanCheckIn);
        Map(m => m.CanCheckOut);
    }
}

更多信息在这里:CsvHelper Mapping

关于c# - 使用 csvHelper 序列化子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24113449/

相关文章:

c# - 将 DLL Controller 添加到 ASP.NET MVC 项目

c# - 如何在 Asp.Net Core 2.2 中将 [FromHeader] 属性与自定义模型绑定(bind)一起使用

c# - 将数据导出到具有固定长度记录的文本文件

c# - Visual Studio 2010 只能运行 4.0 单元测试吗?

c# - C# 中的 JSON 字符串到 CSV 和 CSV 到 JSON 的转换

c# - 在字典的 linq 迭代过程中,什么可能导致堆栈溢出?

c# - 无法加载文件或程序集 'CsvHelper'(C#、VS2019、CSVHelper)

CsvHelper 仅获取标题行

c# - 使用 CsvHelper 可以将空格转换为可为 null 吗?

c# - 使用 csvhelper 进行映射/写入协助