Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Persistence/3.3/Default/CompositeSerializers/EnumSerializer.cs @ 17578

Last change on this file since 17578 was 17180, checked in by swagner, 5 years ago

#2875: Removed years in copyrights

File size: 2.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using HeuristicLab.Persistence.Core;
25using HEAL.Attic;
26using HeuristicLab.Persistence.Interfaces;
27
28namespace HeuristicLab.Persistence.Default.CompositeSerializers {
29
30  [StorableType("1DBD47D9-312B-4572-8B66-C3BFFD004FD6")]
31  internal sealed class EnumSerializer : ICompositeSerializer {
32
33    [StorableConstructor]
34    private EnumSerializer(StorableConstructorFlag _) { }
35    public EnumSerializer() { }
36
37    public int Priority {
38      get { return 100; }
39    }
40
41    public bool CanSerialize(Type type) {
42      return type.IsEnum || type == typeof(Enum);
43    }
44
45    public string JustifyRejection(Type type) {
46      return "not an enum and not System.Enum";
47    }
48
49    public IEnumerable<Tag> CreateMetaInfo(object obj) {
50      yield return new Tag(Enum.Format(obj.GetType(), obj, "G"));
51    }
52
53    public IEnumerable<Tag> Decompose(object obj) {
54      return new Tag[] { };
55    }
56
57    public object CreateInstance(Type t, IEnumerable<Tag> metaInfo) {
58      IEnumerator<Tag> it = metaInfo.GetEnumerator();
59      try {
60        it.MoveNext();
61        return Enum.Parse(t, (string)it.Current.Value);
62      }
63      catch (InvalidOperationException e) {
64        throw new PersistenceException("not enough meta information to recstruct enum", e);
65      }
66      catch (InvalidCastException e) {
67        throw new PersistenceException("invalid meta information found while trying to reconstruct enum", e);
68      }
69    }
70
71    public void Populate(object instance, IEnumerable<Tag> elements, Type t) {
72      // Enums are already populated during instance creation.
73    }
74  }
75}
Note: See TracBrowser for help on using the repository browser.