Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 2993 was 2993, checked in by epitzer, 14 years ago

add justifications for rejecting a type for serialization in ICompositeSerializer (#548)

File size: 2.0 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
[2993]28    public string JustifyRejection(Type type) {
29      if (!ReflectionTools.HasDefaultConstructor(type))
30        return "no default constructor";
31      if (type.GetInterface(typeof(IEnumerable).FullName) == null)
32        return "interface IEnumerable not implemented";
33      if (type.GetMethod("Add") == null)
34        return "no 'Add()' method";     
35      return "no 'Add()' method with one argument";
36    }
37
[1553]38    public IEnumerable<Tag> CreateMetaInfo(object o) {
39      return new Tag[] { };
40    }
41
[1542]42    public IEnumerable<Tag> Decompose(object obj) {
[1454]43      foreach (object o in (IEnumerable)obj) {
[1790]44        yield return new Tag(o);
[1454]45      }
46    }
47
[1553]48    public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
[1454]49      return Activator.CreateInstance(type, true);
50    }
51
[1553]52    public void Populate(object instance, IEnumerable<Tag> tags, Type type) {
[1454]53      MethodInfo addMethod = type.GetMethod("Add");
[1625]54      try {
55        foreach (var tag in tags)
56          addMethod.Invoke(instance, new[] { tag.Value });
57      } catch (Exception e) {
58        throw new PersistenceException("Exception caught while trying to populate enumerable.", e);
59      }
[1454]60    }
[1553]61  }
[1790]62}
Note: See TracBrowser for help on using the repository browser.