Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Default/CompositeSerializers/StackSerializer.cs @ 3205

Last change on this file since 3205 was 3036, checked in by epitzer, 14 years ago

make most serializers internal and complete API documentation (#548)

File size: 1.8 KB
Line 
1using System;
2using System.Collections;
3using System.Reflection;
4using HeuristicLab.Persistence.Core;
5using HeuristicLab.Persistence.Interfaces;
6using System.Collections.Generic;
7using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
8using System.IO;
9
10namespace HeuristicLab.Persistence.Default.CompositeSerializers {
11
12  [StorableClass]
13  internal sealed 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 string JustifyRejection(Type type) {
27        return "not Stack or generic Stack<>";
28    }
29
30    public IEnumerable<Tag> CreateMetaInfo(object o) {
31      return new Tag[] { };
32    }
33
34    public IEnumerable<Tag> Decompose(object obj) {
35      MethodInfo addMethod = obj.GetType().GetMethod("Push");
36      object reverseStack = Activator.CreateInstance(obj.GetType(), true);
37      foreach (object o in (IEnumerable)obj) {
38        addMethod.Invoke(reverseStack, new[] { o });
39      }
40      foreach (object o in (IEnumerable)reverseStack) {
41        yield return new Tag(null, o);
42      }
43    }
44
45    public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
46      return Activator.CreateInstance(type, true);
47    }
48
49    public void Populate(object instance, IEnumerable<Tag> tags, Type type) {
50      MethodInfo addMethod = type.GetMethod("Push");
51      try {
52        foreach (var tag in tags)
53          addMethod.Invoke(instance, new[] { tag.Value });
54      } catch (Exception e) {
55        throw new PersistenceException("Exception caught while trying to populate enumerable.", e);
56      }
57    }
58  }
59}
Note: See TracBrowser for help on using the repository browser.