如果您希望能够对任何对象进行一般操作,则可以使用反射。假设在字典中的值是合适的类型,无需转换:
static T GetObject<T>(Dictionary<string, object> dict)
where T : new()
{
var obj = new T();
foreach (var property in typeof(T).GetProperties())
{
var args = new object[1];
var setter = property.GetSetMethod(); // property has a public setter
if (setter != null && dict.TryGetValue(property.Name, out args[0]))
setter.Invoke(obj, args);
}
return obj;
}
然后使用它:
var alexDict = new Dictionary<string, object>
{
{ "ID", 1 },
{ "Name", "Alex" },
};
var alexPerson = GetObject<Person>(alexDict);
退房这个环节,它可以帮助回答你的问题的http://blog.andreloker .de/post/2008/05/03/Anonymous-type-to-dictionary-using-DynamicMethod.aspx – MethodMan 2011-12-30 07:59:44
我想从Select数据库查询中返回对象。 – 2011-12-30 08:02:49
我认为Dictionary类有一个误解。您似乎会将字典的两个不同元素与一个语义对象相对应。你需要的东西似乎是一个Dictionary对象,它有一个映射到Person对象的int对象。 – 2011-12-30 08:02:53