Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Default/CompositeSerializers/Storable/EmptyStorableClassAttribute.cs @ 2990

Last change on this file since 2990 was 1852, checked in by epitzer, 15 years ago

Correct handling of empty storable classes. (#603)

File size: 1.9 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Reflection;
4
5namespace HeuristicLab.Persistence.Default.CompositeSerializers.Storable {
6
7  [AttributeUsage(
8    AttributeTargets.Class,
9    AllowMultiple = false,
10    Inherited = false)]
11  public class EmptyStorableClassAttribute : Attribute {
12
13    private static readonly Dictionary<Type, bool> emptyTypeInfo = new Dictionary<Type, bool>();
14
15    private const BindingFlags BINDING_FLAGS =
16      BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
17
18    /// <summary>
19    /// Check if supplied type is empty (i.e. no properties or fields) or is marked as empty storable.
20    /// This method is not recusrice and does not check if base types are also empty.
21    /// </summary>   
22    public static bool IsEmptyStorable(Type type) {
23      if (emptyTypeInfo.ContainsKey(type))
24        return emptyTypeInfo[type];
25      if (type == typeof(object)) {
26        return true;
27      }
28      foreach (var attribute in type.GetCustomAttributes(false)) {       
29        if (attribute as EmptyStorableClassAttribute != null) {
30          emptyTypeInfo.Add(type, true);
31          return true;
32        }
33      }     
34      foreach (MemberInfo memberInfo in type.GetMembers(BINDING_FLAGS)) {
35        if (
36          memberInfo.MemberType == MemberTypes.Field && IsModifiableField((FieldInfo)memberInfo) ||         
37          memberInfo.MemberType == MemberTypes.Property && IsModifiableProperty((PropertyInfo)memberInfo) ) {
38          emptyTypeInfo.Add(type, false);
39          return false;
40        }         
41      }     
42      emptyTypeInfo.Add(type, true);
43      return true;           
44    }
45
46    public static bool IsModifiableField(FieldInfo fi) {     
47      return !fi.IsLiteral && !fi.IsInitOnly;
48    }
49    public static bool IsModifiableProperty(PropertyInfo pi) {
50      return pi.CanWrite;
51    }
52  }
53}
Note: See TracBrowser for help on using the repository browser.