Created
August 7, 2012 09:51
-
-
Save kamyar1979/3284026 to your computer and use it in GitHub Desktop.
The famous, widely needed, DynamicDictionary class.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace System.Dynamic | |
{ | |
using System; | |
using System.Collections.Generic; | |
public class DynamicDictionary : DynamicObject | |
{ | |
private Dictionary<string, object> items; | |
public DynamicDictionary() | |
{ | |
this.items = new Dictionary<string, object>(); | |
} | |
public void Add(string key, object value) | |
{ | |
items.Add(key, value); | |
} | |
public bool ContainsKey(string key) | |
{ | |
return items.ContainsKey(key); | |
} | |
public bool Remove(string key) | |
{ | |
return items.Remove(key); | |
} | |
public object this[string key] | |
{ | |
get | |
{ | |
return items[key]; | |
} | |
set | |
{ | |
items[key] = value; | |
} | |
} | |
public void Clear() | |
{ | |
items.Clear(); | |
} | |
public int Count | |
{ | |
get { return items.Count; } | |
} | |
public bool IsReadOnly | |
{ | |
get { return ((ICollection<KeyValuePair<string, object>>)items).IsReadOnly; } | |
} | |
public bool Remove(KeyValuePair<string, object> item) | |
{ | |
return ((ICollection<KeyValuePair<string, object>>)items).Remove(item); | |
} | |
public override bool TryGetMember(GetMemberBinder binder, out object result) | |
{ | |
return items.TryGetValue(binder.Name, out result); | |
} | |
public override bool TrySetMember(SetMemberBinder binder, object value) | |
{ | |
if (items.ContainsKey(binder.Name)) | |
{ | |
items[binder.Name] = value; | |
return true; | |
} | |
return false; | |
} | |
public override IEnumerable<string> GetDynamicMemberNames() | |
{ | |
var iter= items.GetEnumerator(); | |
while (iter.MoveNext()) | |
{ | |
yield return iter.Current.Key; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment