/
ConcreteTypeCreator.cs
74 lines (63 loc) · 2.6 KB
/
ConcreteTypeCreator.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
73
74
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Simple.Data.Extensions;
using System.Collections;
namespace Simple.Data
{
internal class ConcreteTypeCreator
{
private static readonly ConcurrentDictionary<Type, ConcreteTypeCreator> Cache =
new ConcurrentDictionary<Type, ConcreteTypeCreator>();
private readonly Type _concreteType;
private ConcreteTypeCreator(Type concreteType)
{
_concreteType = concreteType;
}
public Type ConcreteType
{
get { return _concreteType; }
}
public static ConcreteTypeCreator Get(Type concreteType)
{
return Cache.GetOrAdd(concreteType, type => new ConcreteTypeCreator(type));
}
public bool TryCreate(IDictionary<string, object> data, out object result)
{
bool anyPropertiesSet = false;
object obj = Activator.CreateInstance(_concreteType);
object value;
foreach (var propertyInfo in _concreteType.GetProperties().Where(pi => CanSetProperty(pi, data)))
{
value = data[propertyInfo.Name];
if (ConcreteCollectionTypeCreator.IsCollectionType(propertyInfo.PropertyType))
{
if (!ConcreteCollectionTypeCreator.TryCreate(propertyInfo.PropertyType, (IEnumerable)value, out value))
continue;
}
else
{
var subData = value as IDictionary<string, object>;
if (subData != null && !ConcreteTypeCreator.Get(propertyInfo.PropertyType).TryCreate(subData, out value))
continue;
}
if (value != null && propertyInfo.PropertyType != value.GetType() && !propertyInfo.PropertyType.IsEnum)
{
value = Convert.ChangeType(value, propertyInfo.PropertyType);
}
propertyInfo.SetValue(obj, value, null);
anyPropertiesSet = true;
}
result = anyPropertiesSet ? obj : null;
return anyPropertiesSet;
}
private static bool CanSetProperty(PropertyInfo propertyInfo, IDictionary<string, object> data)
{
return data.ContainsKey(propertyInfo.Name) &&
!(propertyInfo.PropertyType.IsValueType && data[propertyInfo.Name] == null);
}
}
}