Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Default/CompositeSerializers/EnumerableSerializer.cs @ 1893

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

Namespace refactoring: rename formatters & decomposers -> primitive and composite serializers. (#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;
[1823]7using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[1705]8using HeuristicLab.Persistence.Auxiliary;
[1454]9
[1823]10namespace HeuristicLab.Persistence.Default.CompositeSerializers {
[1454]11
[1563]12  [EmptyStorableClass]
[1823]13  public class EnumerableSerializer : ICompositeSerializer {
[1454]14
[1539]15    public int Priority {
16      get { return 100; }
17    }
18
19
[1823]20    public bool CanSerialize(Type type) {
[1454]21      return
[1705]22        ReflectionTools.HasDefaultConstructor(type) &&
[1454]23        type.GetInterface(typeof(IEnumerable).FullName) != null &&
24        type.GetMethod("Add") != null &&
[1790]25        type.GetMethod("Add").GetParameters().Length == 1;
[1454]26    }
27
[1553]28    public IEnumerable<Tag> CreateMetaInfo(object o) {
29      return new Tag[] { };
30    }
31
[1542]32    public IEnumerable<Tag> Decompose(object obj) {
[1454]33      foreach (object o in (IEnumerable)obj) {
[1790]34        yield return new Tag(o);
[1454]35      }
36    }
37
[1553]38    public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
[1454]39      return Activator.CreateInstance(type, true);
40    }
41
[1553]42    public void Populate(object instance, IEnumerable<Tag> tags, Type type) {
[1454]43      MethodInfo addMethod = type.GetMethod("Add");
[1625]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      }
[1454]50    }
[1553]51  }
[1790]52}
Note: See TracBrowser for help on using the repository browser.