使用CsvHelper和ClassMap将对象模型映射到输出。尝试通过lambda表达式动态生成映射。到目前为止:
public class BaseClassMap<TClass> : ClassMap<TClass> where TClass : class
{
public BaseClassMap(List<string> columns)
{
var index = 0;
PropertyInfo[] props = typeof(TClass).GetProperties();
foreach (PropertyInfo prop in props)
{
index = columns.IndexOf(prop.Name);
if (index != -1)
{
var columnAttribute = prop.GetCustomAttributes(false).FirstOrDefault(a => a.GetType() == typeof(ColumnAttribute)) as ColumnAttribute;
var parameterExpression = Expression.Parameter(typeof(TClass), "x");
var memberExpression = Expression.PropertyOrField(parameterExpression, prop.Name);
var memberExpressionConversion = Expression.Convert(memberExpression, typeof(object));
var lambda = Expression.Lambda<Func<TClass, object>>(memberExpressionConversion, parameterExpression);
Map<object>(lambda).Index(index).Name(columnAttribute != null ? columnAttribute.Name : prop.Name);
}
}
}
}
正在获取:
无法将类型为
CsvHelper.Configuration.MemberMap 2[KXL_CDMS_svc.Data.Entities.ExpTempApplication.TempEnvPermitTrackingCdms,System.String]
的对象转换为类型为CsvHelper.Configuration.MemberMap 2[KXL_CDMS_svc.Data.Entities.ExpTempApplication.TempEnvPermitTrackingCdms,System.Object]
。
at
Map<object>(lambda).Index(index).Name(GetTitle(columnAttribute != null ? columnAttribute.Name : prop.Name));
lambda表达式的新特性。有什么建议吗?
您只需要使用Map
方法的其他重载。
public class BaseClassMap<TClass> : ClassMap<TClass> where TClass : class
{
public BaseClassMap(List<string> columns)
{
var index = 0;
PropertyInfo[] props = typeof(TClass).GetProperties();
foreach (PropertyInfo prop in props)
{
index = columns.IndexOf(prop.Name);
if (index != -1)
{
var columnAttribute = prop.GetCustomAttributes(false).FirstOrDefault(a => a.GetType() == typeof(ColumnAttribute)) as ColumnAttribute;
Map(typeof(TClass), prop).Name(columnAttribute != null ? columnAttribute.Name : prop.Name);
}
}
}
}