Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 1705 was 1705, checked in by epitzer, 15 years ago

Check for default constructor in all decomposers to ensure failure during serialization instead of deserialization. (#606)

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.Decomposers.Storable;
8using HeuristicLab.Persistence.Auxiliary;
9
10namespace HeuristicLab.Persistence.Default.Decomposers {
11
12  [EmptyStorableClass]
13  public class EnumerableDecomposer : IDecomposer {
14
15    public int Priority {
16      get { return 100; }
17    }
18
19
20    public bool CanDecompose(Type type) {
21      return
22        ReflectionTools.HasDefaultConstructor(type) &&
23        type.GetInterface(typeof(IEnumerable).FullName) != null &&
24        type.GetMethod("Add") != null &&
25        type.GetMethod("Add").GetParameters().Length == 1 &&
26        type.GetConstructor(
27          BindingFlags.Public |
28          BindingFlags.NonPublic |
29          BindingFlags.Instance,
30          null, Type.EmptyTypes, null) != null;
31    }
32
33    public IEnumerable<Tag> CreateMetaInfo(object o) {
34      return new Tag[] { };
35    }
36
37    public IEnumerable<Tag> Decompose(object obj) {
38      foreach (object o in (IEnumerable)obj) {
39        yield return new Tag(null, o);
40      }
41    }
42
43    public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
44      return Activator.CreateInstance(type, true);
45    }
46
47    public void Populate(object instance, IEnumerable<Tag> tags, Type type) {
48      MethodInfo addMethod = type.GetMethod("Add");
49      try {
50        foreach (var tag in tags)
51          addMethod.Invoke(instance, new[] { tag.Value });
52      } catch (Exception e) {
53        throw new PersistenceException("Exception caught while trying to populate enumerable.", e);
54      }
55    }
56  }
57}
Note: See TracBrowser for help on using the repository browser.