【问题标题】:How to build a classmap at runtime for nested properties如何在运行时为嵌套属性构建类映射
【发布时间】:2021-05-06 11:50:45
【问题描述】:

假设我有这样的数据结构:

public class Foo
{
   public Bar A {get;set;}
   public Bar B {get;set;}
   public int C {get;set;}
}
public class Bar
{
   public int Value {get;set;}
}

和一个包含内容的 CSV 文件

Column1,Column2,Column3
0,1,2
3,4,5

我现在想将 Column1 映射到 A.ValueColumn2B.ValueColumn3C。 我仅限于运行时映射。 对于Column3 -> C,我可以写

var type = typeof(Foo);
var customMap = Activator.CreateInstance(typeof(DefaultClassMap<>).MakeGenericType(type)) as ClassMap;
customMap.Map(type, type.GetProperty("C")).Name("Column3");
csv_reader.Context.RegisterClassMap(customMap);

如何映射第 1 列和第 2 列?

【问题讨论】:

  • 这里的问题不是嵌套类 - 这是可行的,它是 Bar 被重用,所以你不能将 Bar.Value 映射到 2 个不同的列(即使它是 @987654335 的 2 个单独实例@)。如果你可以有 2 个不同的课程,我认为这是可能的(例如 BarABarB)。
  • 那是不可能的。我不控制用户输入什么类型,所以两个Bars 是非常现实的。
  • 我认为你仅限于reading by hand然后
  • 谢谢。我认为这意味着我应该要求它成为一个功能。对我来说这听起来完全不可能。

标签: c# csvhelper


【解决方案1】:

目前你可以这样做。

void Main()
{
    var s = new StringBuilder();
    s.Append("Column1,Column2,Column3\r\n");
    s.Append("0,1,2\r\n");
    s.Append("3,4,5\r\n");
    var config = new CsvConfiguration(CultureInfo.InvariantCulture)
    {
    };
    using (var reader = new StringReader(s.ToString()))
    using (var csv = new CsvReader(reader, config))
    {
        var fooType = typeof(Foo);
        var barType = typeof(Bar);
        
        var fooMapType = typeof(DefaultClassMap<>).MakeGenericType(fooType);
        var barMapType = typeof(DefaultClassMap<>).MakeGenericType(barType);
        
        var map = (ClassMap)ObjectResolver.Current.Resolve(fooMapType);
        map.Map(fooType, fooType.GetProperty("C")).Name("Column3");
        map.References(barMapType, fooType.GetProperty("A")).Data.Mapping.Map(barType, barType.GetProperty("Value")).Name("Column1");
        map.References(barMapType, fooType.GetProperty("B")).Data.Mapping.Map(barType, barType.GetProperty("Value")).Name("Column2");

        csv.Context.RegisterClassMap(map);
        csv.GetRecords<Foo>().ToList().Dump();
    }
}

private class Foo
{
    public Bar A { get; set; }
    public Bar B { get; set; }
    public int C { get; set; }
}

public class Bar
{
    public int Value { get; set; }
}

我正在寻找方法让想要在运行时创建地图的人更轻松。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-07
    • 2021-09-16
    • 2021-07-10
    • 2013-06-14
    • 1970-01-01
    • 2012-09-07
    相关资源
    最近更新 更多