PropBehavior.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace ClaySharp.Behaviors {
  5. public class PropBehavior : ClayBehavior {
  6. readonly Dictionary<object, object> _props = new Dictionary<object, object>();
  7. public override object GetMembers(System.Func<object> proceed, object self, IDictionary<string, object> members) {
  8. foreach (var pair in _props) {
  9. members.Add(pair.Key.ToString(), pair.Value);
  10. }
  11. return proceed();
  12. }
  13. public override object GetMemberMissing(Func<object> proceed, object self, string name) {
  14. object value;
  15. return _props.TryGetValue(name, out value) ? value : null;
  16. }
  17. public override object SetMemberMissing(Func<object> proceed, object self, string name, object value) {
  18. return _props[name] = value;
  19. }
  20. public override object InvokeMemberMissing(Func<object> proceed, object self, string name, INamedEnumerable<object> args) {
  21. if (!args.Any()) {
  22. return GetMemberMissing(proceed, self, name);
  23. }
  24. if (args.Count() == 1) {
  25. SetMemberMissing(proceed, self, name, args.Single());
  26. return self;
  27. }
  28. return proceed();
  29. }
  30. public override object GetIndex(Func<object> proceed, object self, IEnumerable<object> keys) {
  31. if (keys.Count() != 1) proceed();
  32. object value;
  33. return _props.TryGetValue(keys.Single(), out value) ? value : null;
  34. }
  35. public override object SetIndex(Func<object> proceed, object self, IEnumerable<object> keys, object value) {
  36. if (keys.Count() != 1) proceed();
  37. return _props[keys.Single()] = value;
  38. }
  39. }
  40. }