Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Default/CompositeSerializers/Storable/StorableConstructorAttribute.cs @ 2994

Last change on this file since 2994 was 2994, checked in by epitzer, 14 years ago

Make StorableClass attribute compulsory for StorableSerializer to work, add named property StorableClassType to choose between Empty and MarkedOnly, later other options will be added. (#548)

File size: 1.9 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Reflection;
6using HeuristicLab.Persistence.Core;
7
8namespace 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}
Note: See TracBrowser for help on using the repository browser.