Free cookie consent management tool by TermsFeed Policy Generator

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

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

Scrap Storable-based cloning & reorganize namespaces. (#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 Type Type;
16    public readonly object DefaultValue;
17
18    public DataMemberAccessor(
19        MemberInfo memberInfo,
20        StorableAttribute autoStorableAttribute,
21        object obj) {
22      if (memberInfo.MemberType == MemberTypes.Field) {
23        FieldInfo fieldInfo = (FieldInfo)memberInfo;
24        Get = () => fieldInfo.GetValue(obj);
25        Set = value => fieldInfo.SetValue(obj, value);
26        Type = fieldInfo.FieldType;
27      } else if (memberInfo.MemberType == MemberTypes.Property) {
28        PropertyInfo propertyInfo = (PropertyInfo)memberInfo;
29        if (!propertyInfo.CanRead || !propertyInfo.CanWrite) {
30          throw new NotSupportedException(
31            "Storable properties must implement both a Get and a Set Accessor. ");
32        }
33        Get = () => propertyInfo.GetValue(obj, null);
34        Set = value => propertyInfo.SetValue(obj, value, null);
35        Type = propertyInfo.PropertyType;
36      } else {
37        throw new NotSupportedException(
38                "The Storable attribute can only be applied to fields and properties.");
39      }
40      Name = autoStorableAttribute.Name ?? memberInfo.Name;
41      DefaultValue = autoStorableAttribute.DefaultValue;
42    }
43
44    public DataMemberAccessor(
45        string name, Type type, object defaultValue,
46        Getter getter, Setter setter) {
47      Name = name;
48      Type = type;
49      DefaultValue = defaultValue;
50      Get = getter;
51      Set = setter;
52    }
53
54    public DataMemberAccessor(object o) {
55      Name = null;
56      Type = o.GetType();
57      DefaultValue = null;
58      Get = () => o;
59      Set = null;
60    }
61
62    public override string ToString() {
63      return String.Format("DataMember({0}, {1}, {2}, {3}, {4})",
64        Name,
65        Type == null ? "<null>" : Type.FullName,
66        DefaultValue ?? "<null>",
67        Get.Method, Set.Method);
68    }
69  }
70
71}
Note: See TracBrowser for help on using the repository browser.