Free cookie consent management tool by TermsFeed Policy Generator

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

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

replace Getter and Setter delegates with .NET stock Func<object> and Action<object> (#548)

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