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
RevLine 
[1454]1using System;
2using System.Collections;
3using System.Reflection;
4using HeuristicLab.Persistence.Core;
5using HeuristicLab.Persistence.Interfaces;
6using System.Collections.Generic;
[1623]7using HeuristicLab.Persistence.Default.Decomposers.Storable;
[1454]8
[1566]9namespace HeuristicLab.Persistence.Default.Decomposers {
[1454]10
[1563]11  [EmptyStorableClass]
[1539]12  public class EnumerableDecomposer : IDecomposer {
[1454]13
[1539]14    public int Priority {
15      get { return 100; }
16    }
17
18
[1454]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
[1553]31    public IEnumerable<Tag> CreateMetaInfo(object o) {
32      return new Tag[] { };
33    }
34
[1542]35    public IEnumerable<Tag> Decompose(object obj) {
[1454]36      foreach (object o in (IEnumerable)obj) {
37        yield return new Tag(null, o);
38      }
39    }
40
[1553]41    public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
[1454]42      return Activator.CreateInstance(type, true);
43    }
44
[1553]45    public void Populate(object instance, IEnumerable<Tag> tags, Type type) {
[1454]46      MethodInfo addMethod = type.GetMethod("Add");
[1625]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      }
[1454]53    }
[1553]54  }
[1454]55}
Note: See TracBrowser for help on using the repository browser.