Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Default/Decomposers/Storable/DataMemberAccessor.cs @ 1625

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

Added PersistenceException used consistently for all error conditions in the persistence framework (#548)

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