andrew4582

DynamicDictionary

Apr 8th, 2011
436
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.01 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Dynamic;
  6. using System.Linq;
  7.  
  8. namespace Core.Dynamic {
  9.  
  10.     /// <summary>
  11.     /// DynamicObject class used to allow dynamic operations on a <see cref="IDictionary<string,object>"/> Dictionary
  12.     /// </summary>
  13.     public sealed class DynamicDictionary:DynamicObject {
  14.  
  15.         readonly Func<IDictionary<string,object>> _dataThunk;
  16.         readonly bool _ignoreIfMemberNotfound;
  17.  
  18.         public DynamicDictionary(Func<IDictionary<string,object>> dataThunk,bool ignoreIfMemberNotfound = false) {
  19.             _dataThunk = dataThunk;
  20.             _ignoreIfMemberNotfound = ignoreIfMemberNotfound;
  21.         }
  22.  
  23.         IDictionary<string,object> Data {
  24.             get {
  25.                 IDictionary<string,object> viewData = _dataThunk();
  26.                 Debug.Assert(viewData != null);
  27.                 return viewData;
  28.             }
  29.         }
  30.  
  31.         // Implementing this function improves the debugging experience as it provides the debugger with the list of all
  32.         // the properties currently defined on the object
  33.         public override IEnumerable<string> GetDynamicMemberNames() {
  34.             return Data.Keys.Cast<string>();
  35.         }
  36.  
  37.         public override bool TryGetMember(GetMemberBinder binder,out object result) {
  38.            
  39.             if(_ignoreIfMemberNotfound) {
  40.                 if(!Data.Keys.Contains(binder.Name)) {
  41.                     result = null;
  42.                     return true;
  43.                 }
  44.             }
  45.            
  46.             result = Data[binder.Name];
  47.            
  48.             // since ViewDataDictionary always returns a result even if the key does not exist, always return true
  49.             return true;
  50.         }
  51.  
  52.         public override bool TrySetMember(SetMemberBinder binder,object value) {
  53.             Data[binder.Name] = value;
  54.             // you can always set a key in the dictionary so return true
  55.             return true;
  56.         }
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment