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

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-1 18:12   59   0
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
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP