AutoMapper 泛型转换

2024-04-24

我一直在使用 AutoMapper,并希望进一步进行通用转换;而不是说类似的话

cfg.CreateMap<Container<int>, int>()
    .ConvertUsing(new ContainerConverter<Container<int>, int>());

我宁愿设置 AutoMapper 来知道如何映射任何容器,例如:

cfg.CreateMap<Container<T>, T>()
    .ConvertUsing(new ContainerConverter<Container<T>, T>());

由于从 Container 到 T 的所有转换都是相同的,因此为我正在转换的所有类重新定义此转换是没有意义的。


创建您自己的地图方法作为通用方法,这是一个基本示例,您可以根据需要进行修改

/// <summary>
/// Maps one object into a new object of another type
/// </summary>
public static TResult Map<TSource, TResult>(this TSource source)
    where TSource : class
    where TResult : class, new()
{
    var ret = new TResult();
    source.Map(ret);
    return ret;
}

/// <summary>
/// Maps one object into an existing object of another type
/// </summary>
public static void Map<TSource, TResult>(this TSource source, TResult destination)
    where TSource : class
    where TResult : class
{
    if (Mapper.FindTypeMapFor<TSource, TResult>() == null)
        Mapper.CreateMap<TSource, TResult>();
    Mapper.Map(source, destination);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

AutoMapper 泛型转换 的相关文章

随机推荐