Skip to content

Instantly share code, notes, and snippets.

@prabirshrestha
Created November 26, 2012 23:26
Show Gist options
  • Save prabirshrestha/4151336 to your computer and use it in GitHub Desktop.
Save prabirshrestha/4151336 to your computer and use it in GitHub Desktop.
dictionary reflection get value for key
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