Created
May 31, 2012 21:22
-
-
Save frankhale/2846397 to your computer and use it in GitHub Desktop.
This is a .NET 4 Dynamic Dictionary
This file contains 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
public class DynamicDictionary : DynamicObject | |
{ | |
private Dictionary<string, object> _members = new Dictionary<string, object>(); | |
public bool IsEmpty() | |
{ | |
if (_members.Keys.Count() > 0) | |
{ | |
return false; | |
} | |
return true; | |
} | |
public override IEnumerable<string> GetDynamicMemberNames() | |
{ | |
return _members.Keys; | |
} | |
public IEnumerable<string> GetDynamicMemberNames(string key) | |
{ | |
if (_members.ContainsKey(key)) | |
{ | |
if (_members[key] is DynamicDictionary) | |
return (_members[key] as DynamicDictionary)._members.Keys; | |
} | |
return null; | |
} | |
public Dictionary<string, object> GetDynamicDictionary() | |
{ | |
return _members; | |
} | |
public Dictionary<string, object> GetDynamicDictionary(string key) | |
{ | |
if (_members.ContainsKey(key)) | |
{ | |
if (_members[key] is DynamicDictionary) | |
return (_members[key] as DynamicDictionary)._members; | |
} | |
return null; | |
} | |
public override bool TrySetMember(SetMemberBinder binder, object value) | |
{ | |
if (!_members.ContainsKey(binder.Name)) | |
{ | |
_members.Add(binder.Name, value); | |
} | |
else | |
{ | |
_members[binder.Name] = value; | |
} | |
return true; | |
} | |
public override bool TryGetMember(GetMemberBinder binder, out object result) | |
{ | |
if (_members.ContainsKey(binder.Name)) | |
{ | |
result = _members[binder.Name]; | |
} | |
else | |
{ | |
result = _members[binder.Name] = new DynamicDictionary(); | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment