您可以通过几种方式做到这一点,但如果您希望您的转换器单元可测试,我建议使用继承自ITyperConverter<TSource, TDestination>
.
转换类:
public class SourceToDestinationConverter : ITypeConverter<Source, Destination>
{
private int currentRank;
public SourceToDestinationConverter(int rank)
{
currentRank = rank;
}
public Destination Convert(Source source, Destination destination, ResolutionContext context)
{
destination = new Destination
{
Value1 = source.Value1,
Ranking = currentRank
};
return destination;
}
}
将您的课程设置为 Mapper 配置:
Mapper.Initialize(config =>
{
config.CreateMap<Source, Destination>().ConvertUsing<SourceToDestinationConverter>();
});
Mapper.AssertConfigurationIsValid();
调用方法:
var sources = new List<Source>{
new Source() { Value1 = "test1" },
new Source() { Value1 = "test2" }
};
var destinationsRanked = sources.Select(s => Mapper.Map<Source, Destination>(s, options => options.ConstructServicesUsing(
type => new SourceToDestinationConverter((source.IndexOf(s) + 1))
)));
结果最终成为。
Value1 | Ranking
test1 | 1
test2 | 2