Created
November 26, 2012 23:26
-
-
Save prabirshrestha/4151336 to your computer and use it in GitHub Desktop.
dictionary reflection get value for key
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 ConsoleApplication4 | |
{ | |
using System; | |
using System.Collections.Generic; | |
using ConsoleApplication4.Reflection; | |
using Newtonsoft.Json; | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var obj = new { name = "Prabir" }; | |
var jsonString = JsonConvert.SerializeObject(obj); | |
var json = JsonConvert.DeserializeObject(jsonString); | |
foreach (Type iType in json.GetType().GetInterfaces()) | |
{ | |
if (iType.IsGenericType && iType.GetGenericTypeDefinition() | |
== typeof(IDictionary<,>)) | |
{ | |
Type[] types = ReflectionUtils.GetGenericTypeArguments(iType); | |
Type keyType = types[0]; | |
Type valueType = types[1]; | |
Type genericType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType); | |
var value = typeof(Program).GetMethod("GetDictionaryValue") | |
.MakeGenericMethod(iType.GetGenericArguments()) | |
.Invoke(null, new object[] { json, "name" }); | |
var str = value.ToString(); | |
Console.WriteLine(str); | |
break; | |
} | |
} | |
Console.ReadKey(); | |
} | |
public static object GetDictionaryValue<TKey, TValue>(IDictionary<TKey, TValue> dict, TKey key) | |
{ | |
return dict[key]; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment