1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Linq;
|
---|
4 | using System.Text;
|
---|
5 | using System.Reflection;
|
---|
6 | using HeuristicLab.Persistence.Core;
|
---|
7 |
|
---|
8 | namespace HeuristicLab.Persistence.Default.CompositeSerializers.Storable {
|
---|
9 |
|
---|
10 |
|
---|
11 | /// <summary>
|
---|
12 | /// Indicate that this constructor should be used instead of the default constructor
|
---|
13 | /// when the <code>StorableSerializer</code> instantiates this class during
|
---|
14 | /// deserialization.
|
---|
15 | ///
|
---|
16 | /// The constructor must take exactly one <code>bool</code> argument that will be
|
---|
17 | /// set to <code>true</code> during deserialization.
|
---|
18 | /// </summary>
|
---|
19 | [AttributeUsage(AttributeTargets.Constructor, Inherited = false, AllowMultiple = false)]
|
---|
20 | public sealed class StorableConstructorAttribute : Attribute {
|
---|
21 |
|
---|
22 | private static readonly BindingFlags allConstructors =
|
---|
23 | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
|
---|
24 |
|
---|
25 | private static Dictionary<Type, ConstructorInfo> constructorCache =
|
---|
26 | new Dictionary<Type, ConstructorInfo>();
|
---|
27 |
|
---|
28 |
|
---|
29 | /// <summary>
|
---|
30 | /// Get a designated storable constructor for a type or <code>null</code>.
|
---|
31 | /// </summary>
|
---|
32 | public static ConstructorInfo GetStorableConstructor(Type type) {
|
---|
33 | lock (constructorCache) {
|
---|
34 | if (constructorCache.ContainsKey(type))
|
---|
35 | return constructorCache[type];
|
---|
36 | foreach (ConstructorInfo ci in type.GetConstructors(allConstructors)) {
|
---|
37 | if (ci.GetCustomAttributes(typeof(StorableConstructorAttribute), false).Length > 0) {
|
---|
38 | if (ci.GetParameters().Length != 1 ||
|
---|
39 | ci.GetParameters()[0].ParameterType != typeof(bool))
|
---|
40 | throw new PersistenceException("StorableConstructor must have exactly one argument of type bool");
|
---|
41 | constructorCache[type] = ci;
|
---|
42 | return ci;
|
---|
43 | }
|
---|
44 | }
|
---|
45 | constructorCache[type] = null;
|
---|
46 | return null;
|
---|
47 | }
|
---|
48 | }
|
---|
49 | }
|
---|
50 | }
|
---|