1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Linq;
|
---|
4 | using System.Text;
|
---|
5 | using HeuristicLab.Persistence.Interfaces;
|
---|
6 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
7 | using System.Reflection;
|
---|
8 | using HeuristicLab.Persistence.Core;
|
---|
9 |
|
---|
10 | namespace 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("<", "<").Replace(">", ">");
|
---|
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("<", "<").Replace(">", ">");
|
---|
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 | }
|
---|