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.CompositeSerializers.Storable;
|
---|
8 | using HeuristicLab.Persistence.Auxiliary;
|
---|
9 |
|
---|
10 | namespace HeuristicLab.Persistence.Default.CompositeSerializers {
|
---|
11 |
|
---|
12 | [StorableClass]
|
---|
13 | internal sealed class EnumerableSerializer : ICompositeSerializer {
|
---|
14 |
|
---|
15 | public int Priority {
|
---|
16 | get { return 100; }
|
---|
17 | }
|
---|
18 |
|
---|
19 |
|
---|
20 | public bool CanSerialize(Type type) {
|
---|
21 | return
|
---|
22 | ReflectionTools.HasDefaultConstructor(type) &&
|
---|
23 | type.GetInterface(typeof(IEnumerable).FullName) != null &&
|
---|
24 | type.GetMethod("Add") != null &&
|
---|
25 | type.GetMethod("Add").GetParameters().Length == 1;
|
---|
26 | }
|
---|
27 |
|
---|
28 | public string JustifyRejection(Type type) {
|
---|
29 | if (!ReflectionTools.HasDefaultConstructor(type))
|
---|
30 | return "no default constructor";
|
---|
31 | if (type.GetInterface(typeof(IEnumerable).FullName) == null)
|
---|
32 | return "interface IEnumerable not implemented";
|
---|
33 | if (type.GetMethod("Add") == null)
|
---|
34 | return "no 'Add()' method";
|
---|
35 | return "no 'Add()' method with one argument";
|
---|
36 | }
|
---|
37 |
|
---|
38 | public IEnumerable<Tag> CreateMetaInfo(object o) {
|
---|
39 | return new Tag[] { };
|
---|
40 | }
|
---|
41 |
|
---|
42 | public IEnumerable<Tag> Decompose(object obj) {
|
---|
43 | foreach (object o in (IEnumerable)obj) {
|
---|
44 | yield return new Tag(o);
|
---|
45 | }
|
---|
46 | }
|
---|
47 |
|
---|
48 | public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
|
---|
49 | return Activator.CreateInstance(type, true);
|
---|
50 | }
|
---|
51 |
|
---|
52 | public void Populate(object instance, IEnumerable<Tag> tags, Type type) {
|
---|
53 | MethodInfo addMethod = type.GetMethod("Add");
|
---|
54 | try {
|
---|
55 | foreach (var tag in tags)
|
---|
56 | addMethod.Invoke(instance, new[] { tag.Value });
|
---|
57 | } catch (Exception e) {
|
---|
58 | throw new PersistenceException("Exception caught while trying to populate enumerable.", e);
|
---|
59 | }
|
---|
60 | }
|
---|
61 | }
|
---|
62 | } |
---|