forked from AutoMapper/AutoMapper
/
ReadOnlyCollectionMapper.cs
54 lines (43 loc) · 2.23 KB
/
ReadOnlyCollectionMapper.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System.Collections;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace AutoMapper.Mappers
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Configuration;
public class ReadOnlyCollectionMapper : IObjectMapExpression
{
public static ReadOnlyCollection<TDestinationItem> Map<TSource, TSourceItem, TDestinationItem>(TSource source, ResolutionContext context)
where TSource : IEnumerable
{
if (source == null && context.Mapper.ShouldMapSourceCollectionAsNull(context))
return null;
IList<TDestinationItem> list = new List<TDestinationItem>();
var itemContext = new ResolutionContext(context);
foreach (var item in (IEnumerable)source ?? Enumerable.Empty<object>())
list.Add((TDestinationItem)itemContext.Map(item, default(TDestinationItem), typeof(TSourceItem), typeof(TDestinationItem)));
return new ReadOnlyCollection<TDestinationItem>(list);
}
private static readonly MethodInfo MapMethodInfo = typeof(ReadOnlyCollectionMapper).GetAllMethods().First(_ => _.IsStatic);
public object Map(ResolutionContext context)
{
return
MapMethodInfo.MakeGenericMethod(context.SourceType, TypeHelper.GetElementType(context.SourceType), TypeHelper.GetElementType(context.DestinationType))
.Invoke(null, new[] { context.SourceValue, context });
}
public bool IsMatch(TypePair context)
{
if (!(context.SourceType.IsEnumerableType() && context.DestinationType.IsGenericType()))
return false;
var genericType = context.DestinationType.GetGenericTypeDefinition();
return genericType == typeof (ReadOnlyCollection<>);
}
public Expression MapExpression(Expression sourceExpression, Expression destExpression, Expression contextExpression)
{
return Expression.Call(null, MapMethodInfo.MakeGenericMethod(sourceExpression.Type, TypeHelper.GetElementType(sourceExpression.Type), TypeHelper.GetElementType(destExpression.Type)), sourceExpression, contextExpression);
}
}
}