Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Core/DataMemberAccessor.cs @ 1566

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

Format white space. (Ctrl-K, Ctrl-D) (#548)

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