You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#运行时如何为嵌套属性构建ClassMap实现CSV列映射

你可以通过传入嵌套属性的PropertyInfo访问链实现嵌套属性的运行时映射,完整实现代码如下:

var type = typeof(Foo);
var customMap = Activator.CreateInstance(typeof(DefaultClassMap<>).MakeGenericType(type)) as ClassMap;

// 原有Column3到C的映射
customMap.Map(type, type.GetProperty("C")).Name("Column3");

// 映射Column1到A.Value
var propertyA = type.GetProperty("A");
var propertyAValue = typeof(Bar).GetProperty("Value");
customMap.Map(type, new [] { propertyA, propertyAValue }).Name("Column1");

// 映射Column2到B.Value
var propertyB = type.GetProperty("B");
var propertyBValue = typeof(Bar).GetProperty("Value");
customMap.Map(type, new [] { propertyB, propertyBValue }).Name("Column2");

// 配置自动实例化嵌套对象,避免A、B为null导致赋值失败(如果Foo构造函数已初始化A、B可省略)
csv_reader.Context.AutoMapConstructsNestedObjects = true;

csv_reader.Context.RegisterClassMap(customMap);

说明

  • Map方法传入的PropertyInfo数组对应从顶层Foo类到目标属性的访问路径,new [] { propertyA, propertyAValue } 就对应 A.Value 这个嵌套属性
  • 低版本CSVHelper的自动实例化配置可能在csv_reader.Configuration下,属性名保持为AutoMapConstructsNestedObjects
  • 也可以直接在Foo的无参构造函数中初始化A和B属性,不需要额外配置自动实例化

内容的提问来源于stack exchange,提问作者stefan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 00:06:03