Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Default/CompositeSerializers/StructSerializer.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.3 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using HeuristicLab.Persistence.Interfaces;
6using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
7using System.Reflection;
8using HeuristicLab.Persistence.Core;
9
10namespace HeuristicLab.Persistence.Default.CompositeSerializers {
11
12  [StorableClass]
13  internal sealed class StructSerializer : ICompositeSerializer {   
14
15    public int Priority {
16      get { return 50; }
17    }
18
19    public bool CanSerialize(Type type) {
20      return type.IsValueType && !type.IsPrimitive && !type.IsEnum && type.IsSealed;     
21    }
22
23    public string JustifyRejection(Type type) {
24      if (!type.IsValueType)
25        return "not a value type";
26      if (type.IsPrimitive)
27        return "type is primitive (int, float, ...)";
28      if (type.IsEnum)
29        return "type is enum";
30      return "type is not sealed";
31    }
32
33    public IEnumerable<Tag> CreateMetaInfo(object obj) {
34      return null;
35    }
36
37    private readonly BindingFlags AllInstanceMembers =
38      BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
39
40    public IEnumerable<Tag> Decompose(object obj) {
41      Type t = obj.GetType();
42      foreach (MemberInfo mi in t.GetMembers(AllInstanceMembers)) {
43        if (mi.MemberType == MemberTypes.Field) {
44          string name = mi.Name.Replace("<", "&lt;").Replace(">", "&gt;");         
45          yield return new Tag(name, ((FieldInfo)mi).GetValue(obj));
46        }
47      }
48    }
49
50    public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
51      return Activator.CreateInstance(type, true);
52    }
53
54    public void Populate(object instance, IEnumerable<Tag> tags, Type type) {
55      foreach (Tag t in tags) {
56        string name = t.Name.Replace("&lt;", "<").Replace("&gt;", ">");
57        MemberInfo[] mis = type.GetMember(name, AllInstanceMembers);
58        if (mis.Length != 1)
59          throw new PersistenceException("ambiguous struct member name " + name);
60        MemberInfo mi = mis[0];
61        if (mi.MemberType == MemberTypes.Field)
62          ((FieldInfo)mi).SetValue(instance, t.Value);       
63        else
64          throw new PersistenceException("invalid struct member type " + mi.MemberType.ToString());
65      }
66    }
67   
68  }
69}
Note: See TracBrowser for help on using the repository browser.