Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Persistence Test/HeuristicLab.Persistence/3.3/Default/CompositeSerializers/StackSerializer.cs @ 4498

Last change on this file since 4498 was 1823, checked in by epitzer, 16 years ago

Namespace refactoring: rename formatters & decomposers -> primitive and composite serializers. (#603)

File size: 1.7 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  [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}
Note: See TracBrowser for help on using the repository browser.