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 System.IO;
|
---|
9 |
|
---|
10 | namespace HeuristicLab.Persistence.Default.CompositeSerializers {
|
---|
11 |
|
---|
12 | [EmptyStorableClass]
|
---|
13 | public class StackSerializer : ICompositeSerializer {
|
---|
14 |
|
---|
15 | public int Priority {
|
---|
16 | get { return 100; }
|
---|
17 | }
|
---|
18 |
|
---|
19 |
|
---|
20 | public bool CanSerialize(Type type) {
|
---|
21 | return type == typeof(Stack) ||
|
---|
22 | type.IsGenericType &&
|
---|
23 | type.GetGenericTypeDefinition() == typeof(Stack<>);
|
---|
24 | }
|
---|
25 |
|
---|
26 | public IEnumerable<Tag> CreateMetaInfo(object o) {
|
---|
27 | return new Tag[] { };
|
---|
28 | }
|
---|
29 |
|
---|
30 | public IEnumerable<Tag> Decompose(object obj) {
|
---|
31 | MethodInfo addMethod = obj.GetType().GetMethod("Push");
|
---|
32 | object reverseStack = Activator.CreateInstance(obj.GetType(), true);
|
---|
33 | foreach (object o in (IEnumerable)obj) {
|
---|
34 | addMethod.Invoke(reverseStack, new[] { o });
|
---|
35 | }
|
---|
36 | foreach (object o in (IEnumerable)reverseStack) {
|
---|
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("Push");
|
---|
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 | }
|
---|