1 | using System;
|
---|
2 | using System.Collections;
|
---|
3 | using System.Reflection;
|
---|
4 | using HeuristicLab.Persistence.Core;
|
---|
5 | using HeuristicLab.Persistence.Interfaces;
|
---|
6 | using System.Collections.Generic;
|
---|
7 |
|
---|
8 | namespace HeuristicLab.Persistence.Default.Decomposers {
|
---|
9 |
|
---|
10 | public class EnumerableCache {
|
---|
11 | readonly List<object> values;
|
---|
12 | int nSet;
|
---|
13 | int count;
|
---|
14 | readonly object enumerable;
|
---|
15 | readonly MethodInfo addMethod;
|
---|
16 |
|
---|
17 | public EnumerableCache(object enumerable, MethodInfo addMethod) {
|
---|
18 | values = new List<object>();
|
---|
19 | this.enumerable = enumerable;
|
---|
20 | this.addMethod = addMethod;
|
---|
21 | count = -1;
|
---|
22 | }
|
---|
23 |
|
---|
24 | public Setter GetNextSetter() {
|
---|
25 | int index = values.Count;
|
---|
26 | values.Add(new object());
|
---|
27 | return v => Set(index, v);
|
---|
28 | }
|
---|
29 |
|
---|
30 | private void Set(int index, object value) {
|
---|
31 | values[index] = value;
|
---|
32 | nSet += 1;
|
---|
33 | if (count >= 0 && nSet >= count)
|
---|
34 | Fill();
|
---|
35 | }
|
---|
36 |
|
---|
37 | public void Terminate() {
|
---|
38 | count = values.Count;
|
---|
39 | if (nSet >= count)
|
---|
40 | Fill();
|
---|
41 | }
|
---|
42 |
|
---|
43 | private void Fill() {
|
---|
44 | foreach ( object v in values ) {
|
---|
45 | addMethod.Invoke(enumerable, new[] {v});
|
---|
46 | }
|
---|
47 | }
|
---|
48 |
|
---|
49 | }
|
---|
50 |
|
---|
51 | public class EnumerableDecomposer : IDecomposer {
|
---|
52 |
|
---|
53 | public bool CanDecompose(Type type) {
|
---|
54 | return
|
---|
55 | type.GetInterface(typeof(IEnumerable).FullName) != null &&
|
---|
56 | type.GetMethod("Add") != null &&
|
---|
57 | type.GetMethod("Add").GetParameters().Length == 1 &&
|
---|
58 | type.GetConstructor(
|
---|
59 | BindingFlags.Public |
|
---|
60 | BindingFlags.NonPublic |
|
---|
61 | BindingFlags.Instance,
|
---|
62 | null, Type.EmptyTypes, null) != null;
|
---|
63 | }
|
---|
64 |
|
---|
65 | public IEnumerable<Tag> DeCompose(object obj) {
|
---|
66 | foreach (object o in (IEnumerable)obj) {
|
---|
67 | yield return new Tag(null, o);
|
---|
68 | }
|
---|
69 | }
|
---|
70 |
|
---|
71 | public object CreateInstance(Type type) {
|
---|
72 | return Activator.CreateInstance(type, true);
|
---|
73 | }
|
---|
74 |
|
---|
75 | public object Populate(object instance, IEnumerable<Tag> tags, Type type) {
|
---|
76 | MethodInfo addMethod = type.GetMethod("Add");
|
---|
77 | EnumerableCache cache = new EnumerableCache(instance, addMethod);
|
---|
78 | foreach (var tag in tags) {
|
---|
79 | tag.SafeSet(cache.GetNextSetter());
|
---|
80 | }
|
---|
81 | cache.Terminate();
|
---|
82 | return instance;
|
---|
83 | }
|
---|
84 |
|
---|
85 | }
|
---|
86 |
|
---|
87 | }
|
---|