Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Dynamic;
- using System.Linq;
- namespace Core.Dynamic {
- /// <summary>
- /// DynamicObject class used to allow dynamic operations on a <see cref="IDictionary<string,object>"/> Dictionary
- /// </summary>
- public sealed class DynamicDictionary:DynamicObject {
- readonly Func<IDictionary<string,object>> _dataThunk;
- readonly bool _ignoreIfMemberNotfound;
- public DynamicDictionary(Func<IDictionary<string,object>> dataThunk,bool ignoreIfMemberNotfound = false) {
- _dataThunk = dataThunk;
- _ignoreIfMemberNotfound = ignoreIfMemberNotfound;
- }
- IDictionary<string,object> Data {
- get {
- IDictionary<string,object> viewData = _dataThunk();
- Debug.Assert(viewData != null);
- return viewData;
- }
- }
- // Implementing this function improves the debugging experience as it provides the debugger with the list of all
- // the properties currently defined on the object
- public override IEnumerable<string> GetDynamicMemberNames() {
- return Data.Keys.Cast<string>();
- }
- public override bool TryGetMember(GetMemberBinder binder,out object result) {
- if(_ignoreIfMemberNotfound) {
- if(!Data.Keys.Contains(binder.Name)) {
- result = null;
- return true;
- }
- }
- result = Data[binder.Name];
- // since ViewDataDictionary always returns a result even if the key does not exist, always return true
- return true;
- }
- public override bool TrySetMember(SetMemberBinder binder,object value) {
- Data[binder.Name] = value;
- // you can always set a key in the dictionary so return true
- return true;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment