source: branches/Persistence Test/HeuristicLab.Persistence/3.3/Default/CompositeSerializers/StructSerializer.cs @ 2937

Last change on this file since 2937 was 2937, checked in by epitzer, 12 years ago

Add support for serialization of structs (#802)

File size: 2.0 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  [EmptyStorableClass]
13  public 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 IEnumerable<Tag> CreateMetaInfo(object obj) {
24      return null;
25    }
26
27    private readonly BindingFlags AllInstanceMembers =
28      BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
29
30    public IEnumerable<Tag> Decompose(object obj) {
31      Type t = obj.GetType();
32      foreach (MemberInfo mi in t.GetMembers(AllInstanceMembers)) {
33        if (mi.MemberType == MemberTypes.Field) {
34          string name = mi.Name.Replace("<", "&lt;").Replace(">", "&gt;");         
35          yield return new Tag(name, ((FieldInfo)mi).GetValue(obj));
36        }
37      }
38    }
39
40    public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
41      return Activator.CreateInstance(type, true);
42    }
43
44    public void Populate(object instance, IEnumerable<Tag> tags, Type type) {
45      foreach (Tag t in tags) {
46        string name = t.Name.Replace("&lt;", "<").Replace("&gt;", ">");
47        MemberInfo[] mis = type.GetMember(name, AllInstanceMembers);
48        if (mis.Length != 1)
49          throw new PersistenceException("ambiguous struct member name " + name);
50        MemberInfo mi = mis[0];
51        if (mi.MemberType == MemberTypes.Field)
52          ((FieldInfo)mi).SetValue(instance, t.Value);       
53        else
54          throw new PersistenceException("invalid struct member type " + mi.MemberType.ToString());
55      }
56    }
57   
58  }
59}
Note: See TracBrowser for help on using the repository browser.