public static class ReflectionHelper
{
public static IDictionary<string, object> ToDictionary<TModel>(this TModel model)
{
BindingFlags publicAttributes = BindingFlags.Public | BindingFlags.Instance;
Dictionary<string, object> dictionary = new Dictionary<string, object>();
foreach (PropertyInfo property in model.GetType().GetProperties(publicAttributes))
{
if (property.CanRead)
dictionary.Add(property.Name, property.GetValue(model, null));
}
return dictionary;
}
}
public class Test
{
public string Name{get;set;}
}
void Main()
{
Test t = new Test{Name = "Raj Rao"};
foreach(var v in t.ToDictionary())
{
Console.WriteLine(v.Key + ":" + v.Value);
}
var k = new {J="J1",K="K1",L="Lm"};
foreach(var v in k.ToDictionary())
{
Console.WriteLine(v.Key + ":" + v.Value);
}
}