c# - AutoMapper 通用转换

标签 c# generics automapper

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

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

我宁愿将 AutoMapper 设置为知道如何映射任何 Container,例如:

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

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

最佳答案

创建您自己的 map 方法作为泛型,这是一个您可以根据需要修改的基本示例

/// <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);
}

关于c# - AutoMapper 通用转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40287029/

相关文章:

c# - 检查给定类型是否为枚举

c# - 如何使用 dateTimePicker 将日期插入 SQL 数据库日期列?

scala - 如何修复 Scala 中的这种类型不匹配错误?

c# - 如何使用 EntityFramework 5 在导航属性上只深入一层?

c# - 一种类型到另一种类型的映射列表

c# - SignalR hub 是否自托管?

c# - 使用 WebAuthenticationCoreManager 进行 Facebook 身份验证的 url 是什么

c# - 通用类和接口(interface)的非通用版本

java - 带有 Class<?> 参数的 ObjectFactory

c# - 将序列映射到数组时,Automapper 返回对同一对象的引用