Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive_Milestone3/sources/HeuristicLab.Persistence/3.3/Default/CompositeSerializers/EnumerableSerializer.cs @ 4695

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

Namespace refactoring: rename formatters & decomposers -> primitive and composite serializers. (#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.CompositeSerializers.Storable;
8using HeuristicLab.Persistence.Auxiliary;
9
10namespace HeuristicLab.Persistence.Default.CompositeSerializers {
11
12  [EmptyStorableClass]
13  public class EnumerableSerializer : ICompositeSerializer {
14
15    public int Priority {
16      get { return 100; }
17    }
18
19
20    public bool CanSerialize(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    }
27
28    public IEnumerable<Tag> CreateMetaInfo(object o) {
29      return new Tag[] { };
30    }
31
32    public IEnumerable<Tag> Decompose(object obj) {
33      foreach (object o in (IEnumerable)obj) {
34        yield return new Tag(o);
35      }
36    }
37
38    public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
39      return Activator.CreateInstance(type, true);
40    }
41
42    public void Populate(object instance, IEnumerable<Tag> tags, Type type) {
43      MethodInfo addMethod = type.GetMethod("Add");
44      try {
45        foreach (var tag in tags)
46          addMethod.Invoke(instance, new[] { tag.Value });
47      } catch (Exception e) {
48        throw new PersistenceException("Exception caught while trying to populate enumerable.", e);
49      }
50    }
51  }
52}
Note: See TracBrowser for help on using the repository browser.