问题
I've been using AutoMapper and would like to take generic conversion one step further; instead of saying something like
cfg.CreateMap<Container<int>, int>()
.ConvertUsing(new ContainerConverter<Container<int>, int>());
I would rather set the AutoMapper to know how to map any Container, such as:
cfg.CreateMap<Container<T>, T>()
.ConvertUsing(new ContainerConverter<Container<T>, T>());
Since all conversions from Container to T are the same, it would be pointless to re-define this conversion for all of the classes I am converting.
回答1:
Create your own map method as a generic, here is a basic example that you could modify as needed
/// <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);
}
来源:https://stackoverflow.com/questions/40287029/automapper-generic-conversion