[1454] | 1 | using System;
|
---|
| 2 | using System.Reflection;
|
---|
| 3 |
|
---|
| 4 | namespace 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;
|
---|
[1566] | 13 | public readonly string Name;
|
---|
[1454] | 14 | public readonly object DefaultValue;
|
---|
| 15 |
|
---|
| 16 | public DataMemberAccessor(
|
---|
| 17 | MemberInfo memberInfo,
|
---|
[1542] | 18 | StorableAttribute storableAttribute,
|
---|
[1454] | 19 | object obj) {
|
---|
| 20 | if (memberInfo.MemberType == MemberTypes.Field) {
|
---|
| 21 | FieldInfo fieldInfo = (FieldInfo)memberInfo;
|
---|
| 22 | Get = () => fieldInfo.GetValue(obj);
|
---|
[1566] | 23 | Set = value => fieldInfo.SetValue(obj, value);
|
---|
[1454] | 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);
|
---|
[1566] | 31 | Set = value => propertyInfo.SetValue(obj, value, null);
|
---|
[1454] | 32 | } else {
|
---|
| 33 | throw new NotSupportedException(
|
---|
| 34 | "The Storable attribute can only be applied to fields and properties.");
|
---|
| 35 | }
|
---|
[1542] | 36 | Name = storableAttribute.Name ?? memberInfo.Name;
|
---|
| 37 | DefaultValue = storableAttribute.DefaultValue;
|
---|
[1454] | 38 | }
|
---|
| 39 |
|
---|
| 40 | public DataMemberAccessor(
|
---|
| 41 | string name, object defaultValue,
|
---|
| 42 | Getter getter, Setter setter) {
|
---|
[1566] | 43 | Name = name;
|
---|
[1454] | 44 | DefaultValue = defaultValue;
|
---|
| 45 | Get = getter;
|
---|
| 46 | Set = setter;
|
---|
| 47 | }
|
---|
| 48 |
|
---|
| 49 | public DataMemberAccessor(object o) {
|
---|
[1566] | 50 | Name = null;
|
---|
[1454] | 51 | DefaultValue = null;
|
---|
| 52 | Get = () => o;
|
---|
| 53 | Set = null;
|
---|
| 54 | }
|
---|
| 55 |
|
---|
| 56 | public DataMemberAccessor(object o, string name) {
|
---|
[1566] | 57 | Name = name;
|
---|
[1454] | 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 | } |
---|