Free cookie consent management tool by TermsFeed Policy Generator

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

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

make most serializers internal and complete API documentation (#548)

File size: 2.0 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  [StorableClass]
13  internal sealed 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 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
38    public IEnumerable<Tag> CreateMetaInfo(object o) {
39      return new Tag[] { };
40    }
41
42    public IEnumerable<Tag> Decompose(object obj) {
43      foreach (object o in (IEnumerable)obj) {
44        yield return new Tag(o);
45      }
46    }
47
48    public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
49      return Activator.CreateInstance(type, true);
50    }
51
52    public void Populate(object instance, IEnumerable<Tag> tags, Type type) {
53      MethodInfo addMethod = type.GetMethod("Add");
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      }
60    }
61  }
62}
Note: See TracBrowser for help on using the repository browser.