Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Default/Decomposers/EnumerableDecomposer.cs @ 1688

Last change on this file since 1688 was 1683, checked in by epitzer, 16 years ago

Fix StackDecomposer, reverse collection before serialization (#603)

File size: 1.6 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.Decomposers.Storable;
8
9namespace 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}
Note: See TracBrowser for help on using the repository browser.