您的位置:首页 > 编程语言 > C#

C#中属性PropertyInfo的使用,Dictionary转为Model实例

2015-09-29 14:00 405 查看
Dictionary<string, object> dic = new Dictionary<string, object>();

  dic.Add("Id",100);

  dic.Add("Name", "keso");

  dic.Add("Group", "程序员");

  转换字典方法:

public static T ConvertDic<T>(Dictionary<string, object> dic)
{
T model = Activator.CreateInstance<T>();
PropertyInfo[] modelPro = model.GetType().GetProperties();
if (modelPro.Length > 0 && dic.Count() > 0)
{
for (int i = 0; i < modelPro.Length; i++)
{
if (dic.ContainsKey(modelPro[i].Name))
{
modelPro[i].SetValue(model, dic[modelPro[i].Name], null);
}
}
}
return model;
}
  最后的调用:

  User user = ConvertDic<User>(dic);
http://www.51testing.com/html/24/n-933924-3.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: