root / trunk / Pithos.Core / DynamicDictionary.cs @ 73cdd135
History | View | Annotate | Download (1.6 kB)
1 |
using System.Collections.Generic; |
---|---|
2 |
using System.Dynamic; |
3 |
|
4 |
namespace Pithos.Core |
5 |
{ |
6 |
public class DynamicDictionary : DynamicObject |
7 |
{ |
8 |
// The inner dictionary. |
9 |
Dictionary<string, object> dictionary |
10 |
= new Dictionary<string, object>(); |
11 |
|
12 |
// This property returns the number of elements |
13 |
// in the inner dictionary. |
14 |
public int Count |
15 |
{ |
16 |
get |
17 |
{ |
18 |
return dictionary.Count; |
19 |
} |
20 |
} |
21 |
|
22 |
// If you try to get a value of a property |
23 |
// not defined in the class, this method is called. |
24 |
public override bool TryGetMember( |
25 |
GetMemberBinder binder, out object result) |
26 |
{ |
27 |
// Converting the property name to lowercase |
28 |
// so that property names become case-insensitive. |
29 |
string name = binder.Name.ToLower(); |
30 |
|
31 |
// If the property name is found in a dictionary, |
32 |
// set the result parameter to the property value and return true. |
33 |
// Otherwise, return false. |
34 |
return dictionary.TryGetValue(name, out result); |
35 |
} |
36 |
|
37 |
// If you try to set a value of a property that is |
38 |
// not defined in the class, this method is called. |
39 |
public override bool TrySetMember( |
40 |
SetMemberBinder binder, object value) |
41 |
{ |
42 |
// Converting the property name to lowercase |
43 |
// so that property names become case-insensitive. |
44 |
dictionary[binder.Name.ToLower()] = value; |
45 |
|
46 |
// You can always add a value to a dictionary, |
47 |
// so this method always returns true. |
48 |
return true; |
49 |
} |
50 |
} |
51 |
} |