AutoMapper通用转换 [英] AutoMapper generic conversion
本文介绍了AutoMapper通用转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在使用AutoMapper,并且希望将通用转换更进一步.而不是说类似
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>());
我宁愿将AutoMapper设置为知道如何映射任何Container,例如:
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>());
由于从Container到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.
推荐答案
创建一个通用的地图方法,这是一个基本示例,您可以根据需要进行修改
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);
}
这篇关于AutoMapper通用转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文