1 | using System;
|
---|
2 | using System.Reflection;
|
---|
3 | using HeuristicLab.Persistence.Core;
|
---|
4 |
|
---|
5 | namespace HeuristicLab.Persistence.Default.CompositeSerializers.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(MemberInfo memberInfo, string name, object defaultvalue, object obj) {
|
---|
15 | Name = name;
|
---|
16 | DefaultValue = defaultvalue;
|
---|
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 PersistenceException(
|
---|
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 PersistenceException(
|
---|
31 | "The Storable attribute can only be applied to fields and properties.");
|
---|
32 | }
|
---|
33 | }
|
---|
34 |
|
---|
35 | public DataMemberAccessor(string name, object defaultValue,
|
---|
36 | Func<object> getter, Action<object> setter) {
|
---|
37 | Name = name;
|
---|
38 | DefaultValue = defaultValue;
|
---|
39 | Get = getter;
|
---|
40 | Set = setter;
|
---|
41 | }
|
---|
42 |
|
---|
43 | public DataMemberAccessor(object o) {
|
---|
44 | Name = null;
|
---|
45 | DefaultValue = null;
|
---|
46 | Get = () => o;
|
---|
47 | Set = null;
|
---|
48 | }
|
---|
49 |
|
---|
50 | public DataMemberAccessor(object o, string name) {
|
---|
51 | Name = name;
|
---|
52 | DefaultValue = null;
|
---|
53 | Get = () => o;
|
---|
54 | Set = null;
|
---|
55 | }
|
---|
56 |
|
---|
57 |
|
---|
58 | public override string ToString() {
|
---|
59 | return String.Format("DataMemberAccessor({0}, {1}, {2}, {3})",
|
---|
60 | Name,
|
---|
61 | DefaultValue ?? "<null>",
|
---|
62 | Get.Method, Set.Method);
|
---|
63 | }
|
---|
64 | }
|
---|
65 |
|
---|
66 | } |
---|