As part of the project I’m currently working on I had the need to get all the values out of a dictionary without the benefit of typing, so I had to use reflection. Here is the best was I’ve been able to come up with and hopefully it is useful to others.
1
2 private void GetDictionaryValues(object obj)
3 {
4 var t = obj.GetType();
5
6 // Handle dictionaries.
7 if (typeof(IDictionary).IsAssignableFrom(t))
8 {
9 // Get the methods we need to deal with dictionaries.
10 var keys = t.GetProperty("Keys").GetGetMethod().Invoke(obj, null);
11 var item = t.GetProperty("Item");
12 var enumerator = keys.GetType().GetMethod("GetEnumerator").Invoke(keys, null);
13 var moveNext = enumerator.GetType().GetMethod("MoveNext");
14 var current = enumerator.GetType().GetProperty("Current").GetGetMethod();
15
16 // Get all the values.
17 while ((bool)moveNext.Invoke(enumerator, null))
18 {
19 var key = current.Invoke(enumerator, null);
20 var value = item.GetValue(obj, new object[] { key });
21
22 // Do Stuff.
23 }
24 }
25 }
26