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 | using HeuristicLab.Persistence.Default.Decomposers.Storable;
|
---|
8 |
|
---|
9 | namespace HeuristicLab.Persistence.Default.Decomposers {
|
---|
10 |
|
---|
11 | [EmptyStorableClass]
|
---|
12 | public class EnumerableDecomposer : IDecomposer {
|
---|
13 |
|
---|
14 | public int Priority {
|
---|
15 | get { return 100; }
|
---|
16 | }
|
---|
17 |
|
---|
18 |
|
---|
19 | public bool CanDecompose(Type type) {
|
---|
20 | return
|
---|
21 | type.GetInterface(typeof(IEnumerable).FullName) != null &&
|
---|
22 | type.GetMethod("Add") != null &&
|
---|
23 | type.GetMethod("Add").GetParameters().Length == 1 &&
|
---|
24 | type.GetConstructor(
|
---|
25 | BindingFlags.Public |
|
---|
26 | BindingFlags.NonPublic |
|
---|
27 | BindingFlags.Instance,
|
---|
28 | null, Type.EmptyTypes, null) != null;
|
---|
29 | }
|
---|
30 |
|
---|
31 | public IEnumerable<Tag> CreateMetaInfo(object o) {
|
---|
32 | return new Tag[] { };
|
---|
33 | }
|
---|
34 |
|
---|
35 | public IEnumerable<Tag> Decompose(object obj) {
|
---|
36 | foreach (object o in (IEnumerable)obj) {
|
---|
37 | yield return new Tag(null, o);
|
---|
38 | }
|
---|
39 | }
|
---|
40 |
|
---|
41 | public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
|
---|
42 | return Activator.CreateInstance(type, true);
|
---|
43 | }
|
---|
44 |
|
---|
45 | public void Populate(object instance, IEnumerable<Tag> tags, Type type) {
|
---|
46 | MethodInfo addMethod = type.GetMethod("Add");
|
---|
47 | try {
|
---|
48 | foreach (var tag in tags)
|
---|
49 | addMethod.Invoke(instance, new[] { tag.Value });
|
---|
50 | } catch (Exception e) {
|
---|
51 | throw new PersistenceException("Exception caught while trying to populate enumerable.", e);
|
---|
52 | }
|
---|
53 | }
|
---|
54 | }
|
---|
55 | }
|
---|