首页 > 解决方案 > 无法在 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 表达式。有什么建议么?

标签: c#linq-expressionscsvhelper

解决方案


您只需要使用该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);
            }
        }
    }
}

推荐阅读