c# - 无法在 lambda 表达式中转换类型错误的对象 (CsvHelper)
问题描述
使用 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]
。
在
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);
}
}
}
}
推荐阅读
- php - 未选中“管理库存”时,WooCommerce 允许特定类别的延期交货
- c++ - C++ 如何将 int 存储为 char[]
- git - 如何将我的 github 存储库切换到基于令牌的身份验证而不是使用密码?
- node.js - 如何避免循环中的无异步/等待?
- postgresql - 为什么安装 Postgis 扩展后仍然无法使用 Postgis 功能
- phabricator - Phabricator:差异:是否可以使用自定义变更集在没有 git/svn 等的情况下创建评论
- javascript - 逐行读取txt文件并在每一行更新变量
- java - 在 Java 控制台中创建游戏 - CapitalFinder [建议和帮助]
- c++ - 在显式特化中限制声明可以是什么的规范规则在哪里?
- python - 如何在 Tkinter 中添加 Mac 内置声音