-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
ElementTypeHelper.cs
72 lines (59 loc) · 2.49 KB
/
ElementTypeHelper.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using AutoMapper.Configuration;
namespace AutoMapper.Mappers.Internal
{
public static class ElementTypeHelper
{
public static Type GetElementType(Type enumerableType) => GetElementTypes(enumerableType, null)[0];
public static Type[] GetElementTypes(Type enumerableType, ElementTypeFlags flags = ElementTypeFlags.None) =>
GetElementTypes(enumerableType, null, flags);
public static Type GetElementType(Type enumerableType, IEnumerable enumerable) => GetElementTypes(enumerableType, enumerable)[0];
public static Type[] GetElementTypes(Type enumerableType, IEnumerable enumerable,
ElementTypeFlags flags = ElementTypeFlags.None)
{
if (enumerableType.HasElementType)
{
return new[] {enumerableType.GetElementType()};
}
var iDictionaryType = enumerableType.GetDictionaryType();
if (iDictionaryType != null && flags.HasFlag(ElementTypeFlags.BreakKeyValuePair))
{
return iDictionaryType.GetTypeInfo().GenericTypeArguments;
}
var iReadOnlyDictionaryType = enumerableType.GetReadOnlyDictionaryType();
if (iReadOnlyDictionaryType != null && flags.HasFlag(ElementTypeFlags.BreakKeyValuePair))
{
return iReadOnlyDictionaryType.GetTypeInfo().GenericTypeArguments;
}
var iEnumerableType = enumerableType.GetIEnumerableType();
if (iEnumerableType != null)
{
return iEnumerableType.GetTypeInfo().GenericTypeArguments;
}
if (typeof(IEnumerable).IsAssignableFrom(enumerableType))
{
var first = enumerable?.Cast<object>().FirstOrDefault();
return new[] {first?.GetType() ?? typeof(object)};
}
throw new ArgumentException($"Unable to find the element type for type '{enumerableType}'.",
nameof(enumerableType));
}
public static Type GetEnumerationType(Type enumType)
{
return !enumType.IsEnum ? null : enumType;
}
internal static IEnumerable<MethodInfo> GetStaticMethods(this Type type)
{
return type.GetRuntimeMethods().Where(m => m.IsStatic);
}
}
public enum ElementTypeFlags
{
None = 0,
BreakKeyValuePair = 1
}
}