Free cookie consent management tool by TermsFeed Policy Generator

source: branches/New Persistence Exploration/Persistence/Persistence/Core/DataMemberAccessor.cs @ 1419

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

Implement persistence of storables as decomposer. (#506)

File size: 2.2 KB
Line 
1using System;
2using System.Reflection;
3using HeuristicLab.Persistence.Core;
4
5namespace HeuristicLab.Persistence {
6
7  public class DataMemberAccessor {
8
9    public delegate object Getter();
10    public delegate void Setter(object value);
11
12    public readonly Getter Get;
13    public readonly Setter Set;
14    public readonly string Name;   
15    public readonly object DefaultValue;
16
17    public DataMemberAccessor(
18        MemberInfo memberInfo,
19        StorableAttribute autoStorableAttribute,
20        object obj) {
21      if (memberInfo.MemberType == MemberTypes.Field) {
22        FieldInfo fieldInfo = (FieldInfo)memberInfo;
23        Get = () => fieldInfo.GetValue(obj);
24        Set = value => fieldInfo.SetValue(obj, value);       
25      } else if (memberInfo.MemberType == MemberTypes.Property) {
26        PropertyInfo propertyInfo = (PropertyInfo)memberInfo;
27        if (!propertyInfo.CanRead || !propertyInfo.CanWrite) {
28          throw new NotSupportedException(
29            "Storable properties must implement both a Get and a Set Accessor. ");
30        }
31        Get = () => propertyInfo.GetValue(obj, null);
32        Set = value => propertyInfo.SetValue(obj, value, null);       
33      } else {
34        throw new NotSupportedException(
35                "The Storable attribute can only be applied to fields and properties.");
36      }
37      Name = autoStorableAttribute.Name ?? memberInfo.Name;
38      DefaultValue = autoStorableAttribute.DefaultValue;
39    }
40
41    public DataMemberAccessor(
42        string name, object defaultValue,
43        Getter getter, Setter setter) {
44      Name = name;     
45      DefaultValue = defaultValue;
46      Get = getter;
47      Set = setter;
48    }
49
50    public DataMemberAccessor(object o) {
51      Name = null;     
52      DefaultValue = null;
53      Get = () => o;
54      Set = null;
55    }
56
57    public DataMemberAccessor(object o, string name) {
58      Name = name;     
59      DefaultValue = null;
60      Get = () => o;
61      Set = null;
62    }
63
64
65    public override string ToString() {
66      return String.Format("DataMember({0}, {2}, {3}, {4})",
67        Name,
68        DefaultValue ?? "<null>",
69        Get.Method, Set.Method);
70    }
71  }
72
73}
Note: See TracBrowser for help on using the repository browser.